简体   繁体   English

带有CORS和JSON的Node JS空请求主体

[英]Node js empty request body with CORS and JSON

I am posting this topic regarding the problem the title suggests. 我正在发布有关标题所暗示问题的主题。 I have seen several other questions regarding empty request bodies but none of them were helpful to me. 我还看到了有关空请求主体的其他几个问题,但这些问题都对我没有帮助。 Hopefully if I post my own code someone will be able to give me a good tip. 希望如果我发布自己的代码,有人可以给我一个很好的提示。

Basically I have a client using javascript to make CORS HTTPRequests to a Node.js server. 基本上,我有一个使用JavaScript的客户端向Node.js服务器发出CORS HTTPRequests。 Usually these HTTPRequests are posts of JSON objects. 通常,这些HTTPRequest是JSON对象的帖子。

Here a sample code of the client. 这里是客户端的示例代码。

username = document.getElementById("username").value;
password = document.getElementById("password").value;
var str = '{"name":"'+username+'","pass":"'+password+'"}';
var req = new XMLHttpRequest();
req.open("POST","http://xxxx:8099/register",true)
req.setRequestHeader("Content-type", "application/json");
req.onreadystatechange = function() 
{
     //irrelevant
}
req.send(str);

} }

Here is the code of the server. 这是服务器的代码。

var express    = require('express');
var bodyParser = require('body-parser');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}));

// parse application/json
app.use(bodyParser.json());
app.listen(8099);
app.post("/register", function (req, res) {
console.log(req.body); // populated!
console.log(req.body.name);
res.send(200, req.body);
});

Now these are the results I have been getting: 现在,这些是我得到的结果:

If I set the request Content-type to application/json, then on the server I get an empty request body. 如果我将请求的Content-type设置为application / json,那么在服务器上我将得到一个空的请求主体。

If I set the request Content-type to application/x-www-form-urlencoded, then I get a populated body, for example { '{"name":"usernamtest","pass":"123"}': '' }. 如果我将请求的Content-type设置为application / x-www-form-urlencoded,则会得到一个填充的正文,例如{'{“ name”:“ usernamtest”,“ pass”:“ 123”}':' }。

However, if I try to print req.body.name, I will get undefined wich means the body-parser did not properly parse the body to JSON. 但是,如果我尝试打印req.body.name,我将得到未定义的意思,这意味着主体解析器没有正确地将主体解析为JSON。

How will I solve this? 我该如何解决? I just want to end up with a JSON object of those properties in the example. 我只想在示例中以这些属性的JSON对象结束。

For those who read this I thank you for your time. 对于那些阅读本文的人,我感谢您的宝贵时间。 Complements, Ricardo Ferreira da Silva 补编,里卡多·费雷拉·达席尔瓦

Modern web browser have added a new security requirement that help curb unauthorized access to your webservice from another domain. 现代Web浏览器已添加了新的安全要求,可帮助阻止来自其他域的未经授权的Web服务访问。 CSRF (or Cross Site Request Forgery) hacking involves making HTTP requests from another domain to a web service in an attempt to breach server security and gain access to the potentially valuable data stored on a server. CSRF(或跨站点请求伪造)黑客攻击涉及从另一个域向Web服务发出HTTP请求,以试图破坏服务器安全性并获得对存储在服务器上的潜在有价值数据的访问权。 If the browser sees that the request is going to the same Domain as the website that the request is made from, then it allows the request to be made. 如果浏览器发现该请求与发出请求的网站位于同一个域,则它允许发出请求。 If, however, the domains are different and the request involves something other than getting a static file, the browser first checks for permission to access the service from the server. 但是,如果域不同并且请求涉及的不是获取静态文件,则浏览器会首先检查是否允许从服务器访问服务。

CORS headers (or Cross Origin Resource Sharing) are what the server should respond with to notify the browser what is allowed. CORS标头(或跨源资源共享)是服务器应响应的内容,以通知浏览器允许的内容。 CORS can whitelist domains, http methods, and specific headers. CORS可以将域,http方法和特定标头列入白名单。

This process is known as CORS Preflight. 此过程称为CORS Preflight。

Using the following header: 使用以下标头:

Access-Control-Allow-Origin: * 访问控制允许来源:*

Essentially makes it so that all domains have access. 从本质上来说,它使所有域都可以访问。 The web service is completely public. 该Web服务是完全公开的。 This can leave a gaping security hole unless you intend your service to be public. 除非您打算公开服务,否则这可能会留下巨大的安全漏洞。

Access-Control-Request-Method indicates what HTTP methods are permitted. Access-Control-Request-Method指示允许使用哪些HTTP方法。 GET requests are often allowed by default if this is permitted. 如果允许,默认情况下通常会允许GET请求。

Access-Control-Request-Age determines how long the CORS Preflight is good for. Access-Control-Request-Age确定CORS Preflight适用的时间。 This is measured in seconds. 以秒为单位。

Access-Control-Allow-Headers indicates any headers that are accepted by the server. Access-Control-Allow-Headers指示服务器接受的任何标头。

I highly recommend learning about AJAX Hacking and ways to prevent it (if you haven't already). 我强烈建议您学习有关AJAX黑客及其防范方法的信息(如果您还没有的话)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM