我正在尝试从反应前端发布数据来表达节点API。
以下是从反应(前端)到发布数据的代码:
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);
});
}
我可以发布数据并获得两个错误:
前端运行:localhost:3006
后端运行:localhost:3000
如何解决上述问题?
答案 0 :(得分:0)
最后我得到了解决方案:
generateOTPForLogin(phone_number){
console.log('transfer data');
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((response) => response.json())
.then((responseJSON) => {
console.log(responseJSON);
})
.catch((errResp) => {
console.log(errResp)
});
}
在节点方面:
//commented using default cors
// app.use(cors());
// Provided origin of front end in whitelist list
var whitelist = ['http://localhost:3006']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use('/', cors(corsOptions), index_route);