【问题标题】:serving XMLHttp POST request on node js server在节点 js 服务器上提供 XMLHttp POST 请求
【发布时间】:2017-11-04 04:45:20
【问题描述】:

我试图在节点 js 服务器上提供 XMLHttprequest (POST)。

服务器端:

 app.use(bodyParser.urlencoded({extended:true}));
    app.use(bodyParser.json());


    app.post('/count', function(request, response){
      console.log(request.body);      
      response.send(request.body);    
    });

客户端:

<script>
var xmlhttp = new XMLHttpRequest();
var resp = ""
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
        resp = xmlhttp.responseText;
        resp = JSON.parse(resp);
        document.write(resp);
        }
}

var check = "Hello";

function show(){
xmlhttp.open("POST","http://localhost:3000/count",  true);
xmlhttp.send(JSON.stringify(check));
</script>

我得到的输出是 [object Object]

我哪里错了?

【问题讨论】:

  • 试试JSON.stringify(request.body).forEach(console.log) 看看它打印了什么。如果您在客户端使用fetch API,可能会使您的代码更易于推理:developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • 没有理由继续字符串化。我不知道人们从哪里得到这个。
  • 对于初学者,请将document.write(resp) 替换为console.log(resp)。您在浏览器的控制台中看到了什么?
  • Object {} _proto_: Object(替换为 console.log(resp) 后)

标签: javascript node.js post xmlhttprequest


【解决方案1】:

在客户端添加 setrequestheader 解决了这个问题。

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

【讨论】:

    猜你喜欢
    • 2017-08-19
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    相关资源
    最近更新 更多