使用Ajax向Node.js服务器发出POST请求

时间:2018-10-11 15:19:47

标签: javascript html node.js http post

我是Node.js的新手。

我正在尝试对端口8080上本地运行的Node.js服务器发出POST请求。

但这不起作用。

FireFox阻止了我的POST请求,因为它是跨域的

Reason: CORS request not HTTP

这是我的代码:

HTML

<html>
<head>
    <title>Progetto Start</title>
    <script src="..\Controller\Start.js"></script>
</head>
<body>
    <input type="button" id="btPostJSON" value="invia JSON" onclick="SendJSON()"/>
</body>
</html>

Start.js:

function SendJSON() {
xhr = new XMLHttpRequest();
var url = "127.0.0.1:8080";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4 && xhr.status == 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.name)
    }
}
var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
xhr.send(data);
}

Node js服务器:

var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(req.url);
res.end();
console.log(req.url);
}).listen(8080);

我正在将URL打印到控制台,并且仅作为响应来查看它是否有效 已经有人解决了我的问题吗?

2 个答案:

答案 0 :(得分:1)

请注意,只要服务器/ api的域与调用客户端的域不匹配,就需要CORS。如果客户端的端口号与服务器/ api上的端口号不匹配,则域不匹配,并且需要CORS

从这里无耻地拉:[https://bigcodenerd.org/enable-cors-node-js-without-express/][1]

在您的createServer回调中,放置以下内容:

   const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, // 30 days
    /** add other headers as per requirement */
  };

  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
    return;
  }

  if (['GET', 'POST'].indexOf(req.method) > -1) {
    res.writeHead(200, headers);
    res.end('Hello World'); //Replace this with your response logic
    return;

  }

if(req.method ==“ OPTIONS”)块是您的“飞行前”请求。基本上,这仅用于检查资源的cors权限。

还有其他软件包可以为您做类似的事情。用特定的客户端主机名(“ something.com”)替换“ *”,以提高安全性。使用通配符(*)会带来安全风险,因此在将某些产品投入生产之前,您需要将其更改为要允许访问api的任何域或IP地址。

答案 1 :(得分:0)

您缺少URL中的协议。将http://添加到它,它应该可以工作。

var url = "http://127.0.0.1:8080";