我最近创建了一个服务器并将其部署到Heroku。它在Postman和测试基本GET请求时工作正常。但每当我尝试通过客户端的Axios向它发出POST请求时,我都遇到了这个错误。
在我的后端服务器中,我启用了cors,以便它可以发出跨域请求。 Here, on lines 67 and 69, I set up cors before declaring my routes (click here to see the full 'app.js' file on my github.)
我的注册路由器在Postman中工作正常,其响应时间低于30秒,为1877毫秒。
有趣的是,当我在客户端对我的API发出条件GET请求时,它可以正常工作。 (The lines of code where I make aforementioned GET request are on line 222-258 here)
在我的客户端,只要我想在客户端发出POST请求,就会出现问题。以下是我在下图中的网络响应。
如果我转到响应选项卡,它会显示我的POST请求超时30.1秒,尽管在Postman中1.8秒内完成了相同的API请求。
以下是我在index_actions.js
文件中发出POST请求的代码。
import axios from 'axios'
export function register(fields) {
console.log('below are the fields');
console.log(fields);
return function action(dispatch) {
let objArrSkills = Object.keys(fields.form_skills);
let skillsArr = objArrSkills.map(function (value) {
if (fields.form_skills[value] === true && fields.form_skills[value] !== undefined) {
return value;
}
});
let objArrArts = Object.keys(fields.form_arts);
let artsArr = objArrArts.map(function (value) {
if (fields.form_arts[value] === true && fields.form_arts[value] !== undefined) {
return value;
}
});
console.log('artsArr is...' + artsArr);
console.log('skillsArs is...' + skillsArr);
const request = axios({
method: 'post',
url: "https://jammr-backend.herokuapp.com/register",
data: {
firstName: fields.form_first_name,
lastName: fields.form_last_name,
email: fields.form_email,
password: fields.form_password,
skills: skillsArr,
iWantToMake: artsArr,
street: fields.form_address,
city: fields.form_city,
provinceState: fields.form_province,
gender: fields.form_gender,
imLookingFor: ['Acting', 'Drawing', 'Music', 'Writing', 'Programming', 'Videography']
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
return request.then(response => {
console.log('axios call ran! Below is response....');
console.log(response);
dispatch({
type: 'REGISTER',
payload: {
myId: response.data,
fields: fields,
skills: skillsArr,
iWantToMake: artsArr
}
})
},
err => {
if (err) throw err;
})
}
};
一切正常,直到我将Axios转到/register
路线。与此问题相关的文件是here和here。
更新:我进入我的app.js
文件来更改Cors配置。我注释了app.use(cors());
和app.options('*', cors());
并将其替换为此。
/// x-auth is a custom-header in my server-side code
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,x-auth,Accept,content-type,application/json');
next();
});
/// After this line, I declare my routes.
但是,现在我收到此错误Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.