从本地文件向本地主机8080发出请求时出错

时间:2019-06-20 18:59:15

标签: javascript node.js ajax http

每当按下页面上的按钮时,我都会向本地主机创建一个ajax请求。并且我使用nodejs在8080端口上侦听创建了服务器。但是,当我按下按钮时,chrome开发人员工具终端出现以下错误:

Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'null' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

我正在尝试学习如何与服务器通信。我对此很陌生,如果我的问题听起来很荒谬,请对不起。

发出http请求的代码:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("print_here").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "http://localhost:8080", true);
  xhttp.send("first_name");
}

在端口8080上侦听的服务器节点js代码:

var http = require('http');
//create a server object:
http.createServer(function (req, res) {
  res.write('Last_name'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

上述错误消息意味着什么? (发出http请求的文件位于我的桌面上的文件夹中。创建服务器以侦听端口8080的nodejs文件也位于同一文件夹中。)

2 个答案:

答案 0 :(得分:0)

尝试在服务器中允许跨域访问。

http.createServer(function(req,res){
    // Set CORS headers
     res.setHeader('Access-Control-Allow-Origin', '*');
     res.setHeader('Access-Control-Request-Method', '*');
     res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT');
     res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization');
});

答案 1 :(得分:0)

尝试像这样添加“ Access-Control-Allow-Origin”标头

var http = require('http');
//create a server object:
http
  .createServer(function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.write('Last_name'); //write a response to the client
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080