【发布时间】:2020-07-22 18:30:27
【问题描述】:
我偶然发现了一个问题,也许有人可以提供帮助。目前我已经通过 npm 在 react 项目中安装了 axios,并且在向节点后端发送请求时出现以下错误
Access to XMLHttpRequest at 'http://mechanicapp.test:3333/api/manufacturer?pagination=true&perPage=3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value 'false'.
我已经阅读了关于这个问题的早期堆栈溢出帖子,但没有一个能解决我的问题。
我尝试在请求的标头中设置 Access-Control-Allow-Origin 但没有帮助。
w.Header().Set("Access-Control-Allow-Origin", "*")
我正在为我的后端使用 Adonis.js 框架,我想知道是否有人可以帮助我。
我发送请求的代码如下,或许可以帮助你解决查询。
function checkAuthTokenExclusion(arr, url) {
return (arr.indexOf(url) != -1);
}
let responseFormat = {
error: false,
response: {},
}
/*exclusion array, add those url to this array for which you dont want to set token in header*/
var exclusion = ['user-login'];
const axiosRequest = () => {
const defaultOptions = {
baseURL: "http://mechanicapp.test:3333/api/",
/* method: 'get',*/
headers: {
'Content-Type': 'application/json',
},
};
// Create instance
let instance = axios.create(defaultOptions);
// Set the AUTH token for any request
instance.interceptors.request.use(function (config) {
/*the token will be added to header for those url which are not found in the exclusion array*/
if (!checkAuthTokenExclusion(exclusion, config.url)) {
const token = localStorage.getItem('fixlo-access-token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
}
return config;
});
return instance;
};
async function makeRequest(requestType = 'get', url, data = {},optionalConfig = {}) {
let requestObj = null;
switch (requestType) {
case 'get':
/*sample params pass code for get requests*/
/*
axiosRequest().get('/', {
params: {
results: 1,
inc: 'name,email,picture'
}
});*/
requestObj = axiosRequest().get(url, data);
break;
case 'post':
requestObj = axiosRequest().post(url, data,optionalConfig);
break;
case 'put':
requestObj = axiosRequest().put(url, data,optionalConfig);
break;
case 'delete':
requestObj = axiosRequest().delete(url, data);
break;
default:
/*if no params matches in switch case*/
requestObj = axiosRequest().get(url, data);
}
await requestObj.then(callResponse => {
/*success*/
responseFormat.response = callResponse.data;
}).catch(error => {
/*error*/
responseFormat.error = true;
responseFormat.response = error.response.data;
});
return responseFormat;
}
// export default axiosRequest();
export default makeRequest;```
【问题讨论】: