【问题标题】:Ajax - POST request content doesn't get to the serverAjax - POST 请求内容未到达服务器
【发布时间】:2018-07-21 05:07:02
【问题描述】:

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

这是客户端的代码:

$("#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

});

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

{}

对我做错了什么有什么想法吗?

【问题讨论】:

    标签: node.js ajax post request xmlhttprequest


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      相关资源
      最近更新 更多