我正在使用 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 方法(我檢查了開發工具中的 Network 面板,從服務器回傳回應“Added post”,并將我的 json 物件作為有效負載發送),但控制臺仍然回傳此 HTTPErrorResponse :
SyntaxError:JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:7508:51) at ZoneDelegate.invokeTask (ht..
如果服務器功能已成功回傳,此錯誤的原因可能是什么?
uj5u.com熱心網友回復:
服務器可以成功回傳,但是回呼函式 CreateData 期望從服務器回傳一個 JSON 物件。因為回傳的字串不是 JSON,所以拋出了 HTTPErrorResponse。解決方案是將從我的服務器回傳的字串更改為 JSON 物件,如下所示:
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({}) // returns successfully, no error
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403401.html
標籤:
