使用Angular + Express发出POST请求时返回空响应正文
我正在尝试发出一个简单的POST请求,但我从服务器返回一个空响应。我已经筛选了关于这个主题的所有SO问题并尝试了解决方案,但无济于事。
我已经尝试更改请求标头选项以使用'application/x-www-form-urlencoded'
并在我的快递应用程序中将bodyParser设置为app.use(bodyParser.urlencoded({ extended: true }));
,但这也无效。
AUTH-service.service.ts
login(loginInfo: object) {
return this.http.post<loginInfo>(this.loginUrl, { "test": "test" })
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log('An error occured:', error.error.message);
} else {
console.log(`Backend returned code ${error.status}, ` +
`body was ${error.error}`);
}
return throwError('Something bad happened; please try again later.')
}
loginponent.ts(调用登录服务方法)
onSubmit() {
const loginInfo = { username: this.username.value, password: this.password.value };
this.authService.login(loginInfo).subscribe(
resp => { console.log(resp); },
err => { console.log(err); }
)
}
server.js(我在这里定义了路线,但它们不相关)
const express = require('express');
const bodyParser = require('body-parser');
const api = require('./routes/api');
const app = express();
const port = process.env.port || 3000;
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
})
app.use(bodyParser.json());
app.use('/api', api)
app.get('/', function (req, res) {
res.send(JSON.stringify('Hello from server'));
})
app.post('/login', (req, res) => {
let userData = req.body
res.send('Request body: ' + JSON.stringify(userData));
})
app.listen(port, function () {
console.log('Server running on localhost: ' + port);
});
我是控制台记录以下内容:
Backend returned code undefined, body was undefined
Something bad happened; please try again later.
然而,当我尝试使用Postman时,我得到了我期望的响应(即Request body: {}
)
我不确定为什么在通过Postman完成时检索到响应,而不是通过应用程序完成时。
任何帮助表示赞赏。谢谢!
回答如下:你需要在qazxsw poi中为qazxsw poi请求设置qazxsw poi:
body