我第一次嘗試使用 REST API 使 JavaScript 客戶端和 nodeJS 服務器與 Express 進行通信。由于某種原因,我提供的任何引數xhttp.send在到達后端時都會丟失。
在客戶端,我有以下功能:
function changeStatus(station) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api", false);
xhttp.send(`station=${station}`);
window.location.reload();
}
在服務器端如下:
app.post("/api", function (req, res) {
if ("station" in req.query) {
db[req.query.station] = !db[req.query.station];
res.send(
`Station ${req.query.station} changed to ${db[req.query.station]}`
);
} else {
res.send("No station specified");
}
});
無論如何,我都會得到“其他”配置。有什么建議嗎?我也無法弄清楚如何記錄要附加的原始請求。
uj5u.com熱心網友回復:
查詢引數不會丟失。它們不存在。查詢引數在?路徑段之后的 URL 上進行。
http://example.com?this=is&a=set&of=query¶meters=!
當您發出 POST 請求時,您傳遞給的值send()將在請求正文req.body中發送,如果(根據檔案)您設定了合適的正文決議中間件,則可以訪問該請求正文。
您還應該設定一個Content-Type請求標頭來告訴服務器如何決議您發送的正文。XMLHttpRequest如果您將URLSearchParams物件而不是字串傳遞給它,它將自動執行此操作。
客戶端代碼
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api", false);
const body = new URLSearchParams();
body.append("station", station);
xhttp.send(body);
window.location.reload();
服務器端代碼
app.use(express.urlencoded());
app.post("/api", function (req, res) {
if ("station" in req.body) {
話雖如此,您正在發出 Ajax 請求,然后立即重新加載頁面。
Ajax 的重點是在不重新加載頁面的情況下發出請求。
您不妨改用常規<form>提交。它會更簡單。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432071.html
