import {
Injectable
} from '@angular/core';
import {
Http,
XHRBackend,
RequestOptions,
Request,
RequestOptionsArgs,
Response,
Headers
} from '@angular/http';
import {
Observable
} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {
EmployeeSchema
} from '../schemas/EmployeeSchema';
@Injectable()
export class HttpService extends Http {
headers = new Headers();
constructor(public backend: XHRBackend, options: RequestOptions) {
super(backend, options);
let token = localStorage.getItem('realtoken');;
options.headers.set('Authorization', ` ${token}`);
}
post(url: string, body:Object, options ? : RequestOptionsArgs): Observable < Response > {
this.headers.append('Content-Type', 'application/json');
let token = localStorage.getItem('realtoken');
if (typeof url === 'string') {
if (!options) {
options = {
headers: this.headers
};
}
options.headers.set('Authorization', ` ${token}`);
}
return super.post(url, body, options)
.catch(this.catchAuthError(this));
}
private catchAuthError(self: HttpService) {
return (res: Response) => {
if (res.status === 401 || res.status === 403) {
console.log(res);
}
return Observable.throw(res);
};
}
}
&#13;
添加员工时,req.body
内容在服务器端收到时为{}
,这是服务器端代码
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
//schema-models
var employeeCollection = require('../../model/employee.model.js');
var organizationCollection = require('../../model/organization.model.js');
router.post('/new', function(req, res) {
var bodycontent = req.body;
var addcontent = new employeeCollection(add);
console.log(bodycontent); //here req.body is empty {}
addcontent.save(function(err, data) {
if (err) {
res.send(err);
} else {
console.log('data', data);
res.json(data);
}
});
});
module.exports = router;
&#13;
req.body
为空{}
。
答案 0 :(得分:0)
您需要使用bodyParser
而不是仅仅需要它。
使用正文解析器添加.use(...)
。有关详细信息,请参阅文档:
例如:
app.use(bodyParser.json());
答案 1 :(得分:0)
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
//添加bodyparser middlerware
var app = express();
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
//schema-models
var employeeCollection = require('../../model/employee.model.js');
var organizationCollection = require('../../model/organization.model.js');
router.post('/new', function(req, res) {
var bodycontent = req.body;
var addcontent = new employeeCollection(add);
console.log(bodycontent); //here req.body is empty {}
addcontent.save(function(err, data) {
if (err) {
res.send(err);
} else {
console.log('data', data);
res.json(data);
}
});
});
module.exports = router;