我正在尝试发出一个简单的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.')
}
login.component.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而不是通过应用程序进行检索时会检索到响应。
感谢您的帮助。谢谢!
答案 0 :(得分:0)
您需要为ArrayAdapter
中的body
请求设置POST
:
auth-service.service.ts
答案 1 :(得分:0)
尝试使用express.json丢失
app.use(express.json());
和
app.use(bodyParser.urlencoded({
extended: true
}));