【问题标题】:simple ajax request to localhost nodejs server对 localhost nodejs 服务器的简单 ajax 请求
【发布时间】:2014-11-03 20:52:41
【问题描述】:

我写了非常简单的服务器:

/* Creating server */
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

/*Start listening*/
server.listen(8000);

我使用 nodejs 运行它。

现在我想编写简单的客户端,使用 ajax 调用向服务器发送请求并打印响应(Hello World)

这里是clinet的javascript:

$.ajax({
            type: "GET",
            url: "http://127.0.0.1:8000/" ,
            success: function (data) {
            console.log(data.toString);
            }
        });

当我打开客户端 html 文件时,我在控制台中收到以下错误:

XMLHttpRequest cannot load http://127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

我尝试添加以下 ajax 调用:

 $.ajax({
            type: "GET",
            url: "http://127.0.0.1:8000/" ,
            dataType: 'jsonp',
            crossDomain: true,
            success: function (data) {
            console.log(data.toString);
            }
        });

然后我明白了

Resource interpreted as Script but transferred with MIME type text/plain: "http://127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164". 

谁能解释我做错了什么以及如何解决?

非常感谢!

【问题讨论】:

    标签: ajax node.js


    【解决方案1】:

    第一个错误是由CORS(跨域资源共享)策略引起的。所有浏览器的规则是,您不能向 AJAX 中的远程服务器发出请求,而不是向加载脚本/页面的当前服务器发出请求,除非远程服务器通过 Access-Control-Allow-Origin 标头允许它。

    我建议从同一个 Node.js 服务器提供页面。然后它将起作用。例如,当请求到达根/ 页面时,然后提供index.html 文件,否则,提供您想要的任何其他内容。

    var http = require('http'),
        fs = require('fs');
    
    /* Creating server */
    var server = http.createServer(function (request, response) {
        if (request.url == '/' || request.url == '/index.html') {
            var fileStream = fs.createReadStream('./index.html');
    
            fileStream.pipe(response);
        } else {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.end("Hello World\n");
        }
    });
    
    /*Start listening*/
    server.listen(8000);
    

    【讨论】:

    • 感谢您的回答,但是如果 index.html 的内容是动态的并且每个请求都应该不同,我如何将修改后的 index.html 发送给客户端?
    • 我提供的示例非常基础。它假定您的内容静态存储在文件中。当然,您可以提供动态内容,该内容可能基于来自远程服务器(如数据库或远程 Web 服务)的某些数据。您所要做的就是动态地构建内容。我建议您查看Express Node.js 框架,它允许您在有动态内容占位符的地方为template files 提供服务。准备好动态内容后,就可以将其提供给模板引擎。
    • 模板引擎 + Express 将正确呈现您的动态内容并提供给客户端。
    【解决方案2】:

    要克服 CORS,请在您的 node.js 文件中根据您的需要编写以下内容:

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    

    【讨论】:

    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2021-12-12
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多