所以我正在向 nodeJS 應用程式發送一個 POST 請求,我在 Angular 中的請求如下所示:
export class SearchComponent {
constructor(private http: HttpClient) {}
newWord = '';
keyword = '';
onClick() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
.subscribe((data) => {
this.newWord = data;
});
}
}
當我嘗試 console.log 請求時,即使我嘗試了在 stackoverflow 上可以找到的所有解決方案,我在 JSON 中的位置 0 處得到一個 Unexpected token 錯誤,這就是我的 NodeJS 應用程式的設定方式和錯誤:
const bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
next();
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
app.post("/search", (req, res) => {
res.send(req.body);
});
我得到的錯誤是這樣的:
SyntaxError: Unexpected token " in JSON at position 0
at JSON.parse (<anonymous>)....
請注意,如果我不使用 JSON.stringify 沒有發生錯誤但 req 變數是“未定義”,則 this.keyword 從輸入欄位中獲取其值。
uj5u.com熱心網友回復:
假設您正在詢問如何取回資料。我不確定這是否可行,但您可以嘗試一下:
在評論下,看到你的意思是 this.keyword。這是我要做的改變
按軸格式,這可能是不正確的
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
相反,嘗試:
.post('http://localhost:3000/search', {
keyword: this.keyword, // changed this
responseType: 'text',
headers: headers,
})
同樣在您的服務器中,您可以更改為:
const app = express();
app.use(express.json())
app.use(express.text())
app.use(express.urlencoded({ extended: true }))
(現在快遞中包含正文決議器)
mern 堆疊的新手(從未使用過 Angular)有點不確定,但希望能有所幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/498359.html
上一篇:角度發布請求在控制臺中回傳錯誤
