Ajax - POST请求内容无法访问服务器

时间:2018-02-10 15:52:32

标签: node.js ajax post request xmlhttprequest

我遇到的问题是,我尝试在服务器发送请求时发送的内容不会被发送,但请求有效。

以下是客户端的代码:

$("#searchBtn").click(function(e){

    try{
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/search/searchRequest", true);

        console.log(($("#searchedSymptoms").val())) // gets posted in the console correctly

        xhttp.setRequestHeader("Content-type", "text/plain"); // doesn't work without it either
        xhttp.send($("#searchedSymptoms").val());
        //xhttp.send(JSON.stringify($("#searchedSymptoms").val())); // doesn't work either

        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {

                console.log(xhttp.responseText); // gets the correct response from server

            }
            else{
                console.log(xhttp.responseText);
            }
        };
    }
    catch(err){
        console.log(err);
    }


});

这是服务器端代码:

var express = require("express");
var router = express.Router();
router.post("/searchRequest", function(req, res, next){
    console.log("must get the client request:");
    console.log(req.body);
    //console.log(JSON.stringify(req.body)); // doesn't work either

});

在服务器中,输出到控制台的是:

  

{}

对我做错了什么的想法?

1 个答案:

答案 0 :(得分:1)

你需要使用一个文本正文解析器,默认情况下Express不会这样做,这是一个例子,使用几乎相同的服务器端代码:

"use strict";

var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");

router.post("/searchRequest", function(req, res, next){
    console.log("must get the client request:");
    console.log("SearchRequest: " + req.body);
    res.end('ok', 200);
});

var port = 8081;

var app = express();
app.use(bodyParser.text());
app.use(router);
app.listen(port);
console.log("Express listening on port " + port);

您可以使用此处的指南配置文本正文解析器的运行方式: https://www.npmjs.com/package/body-parser#bodyparsertextoptions