我从表单(使用Angularjs)发送请求以创建新用户。它可以在我的集合中工作和插入数据。但我如何设法使用节点js express更新后端部分的数据。例如,我想检查用户名是否免费。当我发送邮件请求时,我正在尝试console.log。但没有什么是记录。
这是我的server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const restify = require('express-restify-mongoose');
//const userRep = require('./front/core/repository/user/user.repository');
// Middleware
const head = require('./back/midleware/headers.config');
// Models
// TODO provide schema when it will be raedy
const userModel = require('./back/models/user.model');
const app = express();
const router = express.Router();
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/users');
// Body parser config
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Headers config
app.use(head.headerConfig);
// Endpoint configuration
restify.serve(router, userModel.UserModel, {
name: 'users',
});
app.use(router);
app.post('/users', (req, res) => {
console.log('req.post')
})
app.post('/users', (req, res) => {
console.log('req.post')
})
app.listen(2000, function () {
console.info('Server is locating on port 2000');
console.info('to access localhost:2000/api/v1');
});
Ajax请求:
import { UserRepository } from '../../core/repository/user/user.repository';
import * as _ from 'lodash';
class HttpExampleController {
constructor(UserRepository) {
this.repository = UserRepository;
this.allUsers = [];
this.user = {};
this.newUser = {
id: 4,
email: "new@email.com",
username: "newUserName",
name: "newName"
};
this.updatedUser = {
email: "updated@email.com",
name: "updatedUserName"
};
this.getAllUsers();
}
getAllUsers() {
this.repository.getAllUsers()
.then(userList => {
this.allUsers = userList;
});
}
// Discuss if we need this method
getUser(userId) {
this.repository.getUser(userId)
.then(user => {
this.user = user;
});
}
createUser(user) {
this.repository.createUser(user)
.then(res => {
this.allUsers.push(res);
});
}
updateUser(user, data) {
let index = _.indexOf(this.allUsers, _.find(this.allUsers, findUser => findUser._id === user._id));
this.repository.updateUser(user._id, data)
.then(res => {
this.allUsers[index] = res;
});
}
deleteUser(user) {
let index = _.indexOf(this.allUsers, _.find(this.allUsers, findUser => findUser._id === user._id));
this.repository.deleteItem(user._id)
.then(res => _.pull(this.allUsers, res));
}
testFunc() {
this.allUsers.shift();
}
}
export { HttpExampleController };