ajax - 向本地主机nodejs服务器发送简单的ajax请求

标签 ajax node.js

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

/* 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". 

任何人都可以解释我做错了什么以及如何解决它?

非常感谢!

最佳答案

要克服 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);

关于ajax - 向本地主机nodejs服务器发送简单的ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25761481/

相关文章:

javascript - 无法从ajax请求中的php返回获得响应

php - 表单验证、php 和 javascript

ajax - 使用 React.js 和 Ajax 在 Laravel 5 中显示验证错误

javascript - 当 Node/Express 中的请求已附加某些内容时,需要 Require 语句吗?

javascript - VS-Code 不会在 Promise 内部出现异常时暂停调试器

javascript - 如果不是AJAX调用的某个文件则重写

node.js - 如何防止 "npm install"或 "npm remove"删除我的个人包裹?

JavaScript - 使用包含异步回调的函数覆盖函数并仍然返回原始值

javascript - NodeJS Bluebird Promise 在处理程序中创建,但未从处理程序返回

javascript - Wordpress AJAX 调用不断返回 0