【发布时间】:2020-12-02 16:51:17
【问题描述】:
Express 收到一个空的 json 字符串 {},我无法弄清楚原因。我已经为 json 解析器尝试了 bodyParser 和 express.json 并得到了相同的结果。我也找不到我的标题有什么问题。下面是相关代码:
HTTP 客户端发送请求
private sendRequest<T>(verb: string, url: string, body?: any)
: Observable<T> {
let myHeaders = new HttpHeaders();
// myHeaders = myHeaders.set("Access-Key", "<secret>");
// myHeaders = myHeaders.set("Application-Names", ["Rapid Recipes", "MSsanto"]);
return this.http.request<T>(verb, url, {
body: JSON.stringify(body), headers: myHeaders })
.pipe(catchError((error: Response) => throwError(`Network Error: ${error.statusText} (${error.status})`)));
}
快递应用
var app = express();
//app.use(bodyParser());
//app.use(bodyParser.json({ limit: 'Smb' }));
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET','POST','OPTIONS','PUT','PATCH','DELETE',);
res.setHeader('Access-Control-Allow-Headers', 'Authorization', 'X-Requested-With, Content-Type', 'application/x-www-form-urlencoded', 'application/json');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
app.post("/:type", function (req, res) {
console.log('The POST was received');
var typeName = req.originalUrl.substring(1).toLowerCase();
var params = {};
params[typeName] = 1;
params["_id"] = 1
console.log("the request bod is " + JSON.stringify(req.body)); //this returns {}
var dbm = dbModel.findOne({}, params);
dbm.updateOne({ $push: { "recipe": req.body } }, function (err, data)
{
if (err) {
res.send(err);
}
else {
res.send(data)
console.log('data saved!');
} } ) }
)
});
【问题讨论】: