NodeJS 对客户端请求的响应 - HTTP

问题描述 投票:0回答:1

我使用

http.createServer(...)
函数在 NodeJS 中创建了一个 HTTP 服务器。从客户端 JavaScript 文件,我使用 localhost url 上的
POST
方法发送了一个查询。服务器已成功接收来自客户端的数据,但现在我无法向客户端发送消息、“成功”/JSON 文件等响应。我已经尝试了许多使用
res.end(message)
res.write()
的方法,但在调用
end()
后它不断停止服务器,并且我的客户端在控制台上抛出错误。我正在 VS Code 上使用 Live Server 运行 HTML 文件。 代码如下:

客户端.js

var xhr = new XMLHttpRequest();
let inputVal;

function load(url, callback) {
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        console.log(xhr.readyState);
        callback(xhr.response);
      }
    }
    xhr.open("POST", url, true);
    responseType = "";
    var body = "name="+inputVal;
    console.log(body);
    xhr.send(body);
}

function alert_user(data)
{
    window.alert("Response Received");
    console.log("OK");
    console.log(data);
}

searchBtn.addEventListener('click', function (e){
    e.preventDefault();
    // to prevent reloading
    inputVal=document.getElementById("name").value;
    load("http://localhost:3000/", alert_user);
});

服务器.js

var http = require('http');
var qs = require('querystring');

http.createServer(function (req, res) {
    if (req.method == "POST") {
        var body = '';
        req.on('data', function (data) {
            body += data;
        });
        var post = qs.parse(body);
        req.on('end', () => {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end('Success');
        });
    }
}).listen(3000);

我正在通过 VS Code Live Server 的 CMD 和 HTML 文件运行我的服务器。

当我使用没有

res.end()
的服务器并继续对我的数据进行一些操作时,它会正确执行所有操作,并且客户端 JS 上没有 CORS 错误。

我还尝试使用 Express 框架创建服务器,当我使用

res.json()
或类似的东西,并在客户端使用
fetch().then().then()
来接收 json 文件作为响应时,它可以完美地工作。 我正在 NodeJS 上编写服务器代码,因为我想在创建服务器的同时使用 NodeJS 的其他功能。 任何人都可以建议可能的错误以及如何调试它们并仅使用 XMLHttpRequest 使其正常工作吗?

编辑: 控制台现在通过将

readyState
设置为 4 显示请求已完成,但我从服务器收到空响应。

javascript node.js xmlhttprequest fetch-api
1个回答
0
投票

问题又出在 CORS 上:-(

这是最终的工作代码...

客户端.js

var xhr = new XMLHttpRequest();
let inputVal;
let searchBtn = document.getElementById("searchBtn");

function load(url, callback) {
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        console.log(xhr.readyState);
        callback(xhr.responseText);
      }
    }
    xhr.open("POST", url, true);
    responseType = "";
    var body = "name="+inputVal;
    console.log(body);
    xhr.send(body);
}

function alert_user(data)
{
    window.alert("Response Received");
    console.log("OK");
    console.log(data);
}

searchBtn.addEventListener('click', function (e){
    e.preventDefault();
    // to prevent reloading
    inputVal=document.getElementById("name").value;
    load("http://localhost:3000/", alert_user);
});

服务器.js

http.createServer(function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method == "POST") {
        //other operations
        res.end("Done");
    }
}).listen(3000);

这有效,客户端在他的控制台上得到响应:-)

(一切都在 VS Code 的实时服务器上运行)

© www.soinside.com 2019 - 2024. All rights reserved.