【发布时间】:2017-10-30 12:36:39
【问题描述】:
我正在尝试从反应前端发布数据以表达节点 API。
下面是从 react(前端)到 post 数据的代码:
generateOTPForLogin(phone_number){
console.log('transfer data');
fetch(
API_URL+'/generateOTP', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
phone_number: phone_number
})
});
}
以下是我在用户控制器中获取请求的代码:
exports.generateOTP = (req,res) => {
console.log('generating otp...',req.body);
// generating otp... { '{"phone_number":"+9999999"}': '' }
}
}
在这里你可以检查我是如何接收数据的,整个 JSON 在请求正文中,键和值是空的。
我怎样才能得到 { "phone_number":"+9999999"} 的响应?
您可以在下面获取应用设置:
import express from 'express';
import path from 'path';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
module.exports= function (app){
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.engine('view engine', require('jade').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
};
请帮助我了解这里的问题。我尝试使用 POSTMAN 发布数据,使用以下设置它工作正常并且我得到了正确的数据:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/generateOTP",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"phone_number": "+999999999"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
我找到了解决方案,但只是部分解决了:
generateOTPForLogin(phone_number){
var details = {
phone_number: "+91"+phone_number
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch( API_URL+'/generateOTP', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).then(function(responseOTP){
console.log("resp:",responseOTP);
alert(responseOTP);
}).catch(function(errorOTP){
console.log("error:",errorOTP); //TypeError: Failed to fetch
alert(errorOTP);
});
}
我可以发布数据并收到两个错误:
- 在 chrome 浏览器中我遇到了这个问题:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:3006' 不允许访问。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
前端运行在:localhost:3006
后端运行在:localhost:3000
- 在 then 和 catch 部分中,在接收响应中的响应时,我无法在 then promise 中获取它,它正在寻找打印:TypeError: Failed to fetch。
我该如何解决以上问题?
【问题讨论】:
-
您没有描述问题或提出问题。什么不起作用?预期什么?
-
请查看更新后的问题
标签: node.js reactjs express body-parser