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

How do you both POST data to a node server and GET a responseText from it?

本文关键字:获取 responseText 服务器 节点 数据 POST      更新时间:2023-09-26

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

在下面的示例中,POST命令使用指定的路径将数据对象发送到服务器。这很有效。什么它不做的是将响应发送回验证数据的客户端。当我运行代码示例时,就绪状态从不超过1(服务器连接已建立)。如果我将POST参数更改为GET,则就绪状态从1到2再到3到4,正如您对responseText值所期望的那样,该值基于路径的设置。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

您可以一次发送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;

软件包.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

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

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

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