[英]req.body is null in expressjs server when sending post request from ionic app
I am developing an ionic app when I am sending a post request using angularjs $http.post to my express js server, I cannot see the data in the req.body. 当我使用angularjs $ http.post向我的express js服务器发送发布请求时,我正在开发一个离子应用程序,我无法在req.body中看到数据。
I am running my server on localhost:3000 我在本地主机上运行服务器:3000
Code in my server for CORS 我的服务器中的CORS代码
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET,PUT,DELETE,POST");
next();
});
My angular Js post request 我的角度Js发布要求
$http.post('http://localhost:3000/signup',{"username":"x","password":"y"}).success(function(res){
console.log(res);
if(res.msg=="success")
{
//do something
}
}
I am able to see data in req.body as "key" like: 我能够在req.body中将数据视为“键”,例如:
{'{"username":"x","password":"y"}':''}
When I am setting the header from ionic app as: 当我将离子应用程序的标头设置为:
$http.defaults.headers.post["Content-Type"] = 'application/x-www-form- urlencoded; charset=UTF-8';
Please let me know how to debug this 请让我知道如何调试
You are getting the entire data as key in req.body
. 您正在将整个数据作为
req.body
键。 This is because the angular request that you are making is wrong. 这是因为您提出的角度要求是错误的。 Here is the part of code that should work
这是应该起作用的代码部分
$http({
url: 'http://localhost:3000/signup',
method: "POST",
data: { username : "a" , password : "b" }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
Well I figured that out I have used this stackoverflow link Ionic framework http post request to parse my data before its send to my server 好吧,我发现我已经使用了这个stackoverflow链接Ionic框架http发布请求来解析我的数据,然后再将其发送到我的服务器
$http.defaults.headers.post["Content-Type"] = 'application/x-www-form-urlencoded; charset=UTF-8';
Object.toparams = function ObjecttoParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: 'http://localhost:3000/signup',
method: "POST",
data: Object.toparams(u)
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.