【发布时间】:2021-12-30 18:10:40
【问题描述】:
我正在使用 Angular 的 HttpClient 向我的 NodeJS 服务器执行 POST 请求,如下所示:
createData(data:any):Observable<any> {
// verifying the content type is need to ensure the JSON object is sent as
// JSON object to NodeJS server
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
// This still throws an HTTPResponse error, -
// SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse
return this._http.post(`${this.apiUrl}`, data, options);
}
而我服务器的 POST 功能是这样设置的:
router.post('/', async (req,res) => {
const body = req.body;
await database.execute(`
INSERT INTO Post (
title,
body,
date_added
) VALUES (
@title,
@body,
NOW()
)
`, {
title: body.title,
body: body.body,
})
res.end('Added post')
})
调用 createData 时,执行 POST 方法(我检查了开发工具中的网络面板,从服务器返回响应“已添加帖子”,并将我的 json 对象作为有效负载发送),但控制台仍然返回此 HTTPErrorResponse:
SyntaxError:在 ZoneDelegate.invokeTask (ht. .
如果服务器函数成功返回,这个错误的原因是什么?
【问题讨论】:
-
您的 Angular 代码期待一个 JSON 响应并尝试对其进行解析,但是您发送回一个字符串“Added post”,它不是有效的 JSON。错误信息有什么不清楚的地方吗?
-
@Andre 你可以将 res.end('Added post') 更改为 res.end({"result":"Added post"})
-
啊,是的,你是对的,我忘记将服务器函数的返回更改为 JSON 对象。谢谢你的指点! @esqew
-
您说得对,谢谢您的回复。 @RajatAggarwal
标签: mysql node.js json angularjs angular-httpclient