簡體   English   中英

如何使用前端ajax通過post方法發送的node.js在服務器端檢索數據?

[英]How to retrieve data on server side with node.js sent by frontend ajax via post method?

我最近開始使用 express 框架學習 node.js 並偶然發現了一個問題。

我正在嘗試一個簡單的查詢搜索 webapp,我想傳遞一段數據(一個 boolean 稱為 all)

從前端平原 javascript 通過 ajax 到服務器端,但當前代碼

我現在寫的,似乎我的數據沒有傳遞到服務器端,

我種的3個console.log全部返回{}。

我在這里缺少什么概念? 我究竟做錯了什么?

如果需要任何其他信息,請告訴我,謝謝。

前端js

window.onload=function(){
console.log("window loaded");
const xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:3000/search", true);
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status==200){
        // code later to be implemented
    }
}
let searchConditions = new SearchConditions(true);
console.log('data='+JSON.stringify(searchConditions));
xhr.send('data='+JSON.stringify(searchConditions));
}

class SearchConditions{
    constructor(all) {
        this.all = all;
    }
}

后端 node.js

// only partial code

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.post('/search', (req, res) => {
    console.log(req.body);
    console.log(req.query);
    console.log(req.params);
});

我的瀏覽器日志

在此處輸入圖像描述

我的后端日志

在此處輸入圖像描述

因為您發送無效數據:

xhr.send('data='+JSON.stringify(searchConditions));

JSON 對象沒有變量聲明。 您的服務器得到的是:

'data = {"all": true }'

這甚至不是一個有效的變量聲明。 您的服務器應該得到的是:

{"all": true}

嘗試發送沒有變量聲明的普通 JSON Object 並將“Content-Type”標頭設置為 json:

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(searchConditions));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM