我有一个客户端角度应用程序,它向节点js服务器发送POST
请求。
order(market: string, price: string, side: string, size: string): Observable<any> {
var payload = { market: market, order: { price: price, side: side, size: size } };
return this.http.post<any>('http://localhost:3000' + "/orders", JSON.stringify(payload))
.pipe(
tap((res: any) => {
console.log(res);
}),
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
}
带有express-generator的nodejs:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post('/orders', (req, res) => {
console.log(req.body)
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
角度应用可以访问nodejs应用中的方法
app.post('/orders', (req, res) => {
console.log(req.body)
});
但req.body
未定义。我在这里做错什么了吗?
答案 0 :(得分:1)
您的后端代码对我来说看起来不错。 我相信问题是由前端代码引起的。特别是这一行:
this.http.post<any>('http://localhost:3000' + "/orders", JSON.stringify(payload))
请勿对要发送到后端的数据进行字符串化处理。像这样更改它:
this.http.post<any>('http://localhost:3000' + "/orders", payload)
答案 1 :(得分:0)
您需要使用body-parser,它是ExpressJS中间件,可让您解析POST请求。这是一个有据可查的问题,您也可以找到类似的S / O问题here