你如何将数据POST到节点服务器并从中获取responseText?

时间:2016-04-30 14:20:37

标签: javascript ajax node.js http express

在以下示例中,我尝试将数据从javascript客户端发送到Express节点服务器,验证数据 针对服务器上的数据库,并在验证完成后作出响应。 newHttpRequest.send中的数据对象(数据) 包含JSON格式的配对值。

在下面的示例中,POST命令使用指定的路径将数据对象发送到服务器。这很好用。什么 它没有做的是将响应发送回客户端验证数据。当我运行代码示例时,就绪状态永远不会 超过1(建立服务器连接)。如果我将POST参数更改为GET,则就绪状态从1进展到2到3 如您所期望的那样使用基于路径设置的responseText值的4。 GET命令的问题是 数据永远不会从客户端发送或由服务器接收。

我的问题是,我是否可以将数据POST到节点服务器并从中获取一个responseText,说明数据已经成功 验证

{ // XMLHttpRequest
  var newHttpRequest = new XMLHttpRequest();
  var path = "http://00.0.0.00:80";

  newHttpRequest.onreadystatechange = function()
  {
    alert("onreadystatechange: " + newHttpRequest.readyState );
    if ( newHttpRequest.readyState === 4 && newHttpRequest.status === 200)
    {
      var myResponseText = newHttpRequest.responseText;
      alert ("responseText: " + myResponseText);
    }
  };

  newHttpRequest.open("POST", path, true);
  newHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  newHttpRequest.setRequestHeader("header_nb", "1");
  newHttpRequest.setRequestHeader("header_ds", "logon");
  newHttpRequest.setRequestHeader( "Content-Type", "application/json; charset=UTF-8" );
  newHttpRequest.send(data);
} // eof code block

2 个答案:

答案 0 :(得分:2)

您可以一次发送POST或GET请求。您可以在发送POST后从服务器获取(接收)数据,也可以在发送POST后发送GET以接收其他一些数据;它只是语义:)

以下是我希望能帮到你的一个例子:

前端(index.html +您修改后的脚本):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    { // XMLHttpRequest
        var newHttpRequest = new XMLHttpRequest();
        var path = "http://0.0.0.0:3000";

        newHttpRequest.onreadystatechange = function()
        {
            alert("onreadystatechange: " + newHttpRequest.readyState );
            if ( newHttpRequest.readyState === 4 && newHttpRequest.status === 418)
            {
                var myResponseText = newHttpRequest.responseText;
                alert ("responseText: " + myResponseText);
            }
        };

        var data = {
            hero: 'Spiderman Spiderman',
            ability: 'He can open a tuna can'
        };

        newHttpRequest.open("POST", path + '/my-post-route', true);
        newHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        newHttpRequest.setRequestHeader("header_nb", "1");
        newHttpRequest.setRequestHeader("header_ds", "logon");
        newHttpRequest.setRequestHeader( "Content-Type", "application/json; charset=UTF-8" );
        newHttpRequest.send(JSON.stringify(data));
    }
</script>
</body>
</html>

后端(index.js,node + express):

'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

var app = express();

// Configure express settings; standard stuff; research what they do if you don't know
app.set('trust proxy', true);
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));
app.use(bodyParser.json({limit: '10mb'}));
app.use(cookieParser());

// Configure routes
app.post('/my-post-route', function (req, res, next) {
    // ... do what you need to do here ...

    console.log(req.headers); // to see what those headers contain

    console.log(req.body); // Look ma! It's Spiderman!

    var ImATeaPot = true;

    if (ImATeaPot)
        return res.status(418).send("I'm a teapot!"); // return to end here (if you are a teapot) and send a string; you can chain status, send and other commands

    res.send("I'm not a teapot! :O"); // Oh yes you are! 
    // send status is 200 by default, so you don't need to set it if that's what you need

    // res.json({ myText: "Hello World!" }); // you can send an object with .json(); also status 200 by default
    // res.status(500).end(); // you can just send a status and no body; always remember to send something or end it or next() if you want to keep going with some other express code
});

// for testing purposes we send the index.html
app.get('/*', (req, res) => res.sendFile(__dirname + '/index.html'));

// Start the server; Listen for requests on the desired port
var server = app.listen(3000, function () {
    return console.log('Hello World!');
});

module.exports = server;

的package.json

{
  "dependencies": {
    "body-parser": "^1.14.1",
    "cookie-parser": "^1.4.0",
    "express": "^4.12.2"
  }
}

在终端:

npm install
node index.js

在浏览器中,转到0.0.0.0:3000

答案 1 :(得分:0)

我在这里看到2个问题。首先,您可能需要在POST调用中添加超时以接收响应。服务器必须响应POST请求,否则您将收到超时错误或内部服务器错误(500)。

其次,你不能在同一个电话中使用POST和GET。当您使用GET而不是POST时,数据变得无关紧要,因为它是一个GET调用,其中数据不会发送到远程端。这就是为什么你可能会收到对GET呼叫的快速响应。

在我看来,你应该验证一次远程HTTP服务器会卷曲命令。