【问题标题】:Unable to send back .json data with Node.js (Cors error)无法使用 Node.js 发回 .json 数据(Cors 错误)
【发布时间】:2015-11-02 21:47:04
【问题描述】:

我开始学习node.js,但我有一点问题。我有一个 ajax 函数,它调用在端口 8001 上侦听的服务器。打开并加载一个 .json 文件后,我想将其发送回页面。对于加载的问题,没有问题,但是当我发送回页面时,出现此错误: 在 Chrome 上“POST http://localhost:8001/net::ERR_CONNECTION_REFUSED”; 在 Firefox 上“...原因:CORS 请求失败。”

这里是我的简单文件 .js 的代码:

    var http = require('http'),
          fs = require('fs'),
         url = require('url');

    http.createServer(function (request, response) {
        var path = url.parse(request.url).pathname;
        console.log("request recieved");
        var obj;
        fs.readFile('../menu.json', 'utf8', function (err, data) {
            if (err) throw err;
            console.log(data);
            obj = JSON.parse(data);
            console.log(obj);
            response.writeHead(200, { "Content-Type": "application/json" });
            response.end(obj, "utf-8");        
        });   

    }).listen(8001);
    console.log("server initialized !!");

我怎样才能让它工作?我也阅读了另一个主题,但我还没有找到解决方案。提前感谢您的时间和耐心。

编辑: 这是ajax调用:

   function testNodeJs() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://localhost:8001/", true);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var string = xmlhttp.responseText;
            alert(string);
        }
    }
    xmlhttp.send();
};

【问题讨论】:

  • 对不起,我刚开始;我也读过这个问题,但我没有使用 express.js ,那我该如何解决?
  • 你必须响应 CORS 授权请求,你可以手动构建它,但通常框架组件更有帮助——也许你应该使用 Express.js

标签: javascript ajax json node.js


【解决方案1】:

试试这个:

response.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" ,"Access-Control-Allow-Methods":"GET, POST","Access-Control-Allow-Headers","X-Requested-With,content-type, Authorization"});

欲了解更多详情,请访问此链接: https://annasob.wordpress.com/2012/01/11/getting-around-cors-with-node-js/

【讨论】:

    【解决方案2】:

    服务器需要发送一个跨域资源共享 (CORS) 标头。对于您的简单情况,这样做可能就足够了

    response.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
    

    但看起来也有一个 NPM 模块可以帮助你,https://www.npmjs.com/package/cors

    关于 CORS 的补充阅读:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

    【讨论】:

    • 我安装了 cors 模块,并应用了您的解决方案,但我不知道为什么它仍然无法正常工作:(
    猜你喜欢
    • 2015-06-28
    • 2018-08-08
    • 2015-03-09
    • 2018-12-04
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2020-04-10
    • 2021-07-02
    相关资源
    最近更新 更多