启用cors的axios获取请求失败

时间:2020-03-27 12:13:55

标签: javascript cors axios

具有2个api。方法POST-登录方法GET-data。并且服务器已启用cors。登录api工作正常,但是使用GET方法调用api时失败。 代码:

-> api登录POST

const login = async (email, password) => {
  console.log("in auth service");
  const userDetail = {
    username:email,
    // email,
    password
  };

  try {
    // unsetHeadersWithUserToken();
    const afterSuccess = await api.post(apiDetail.auth.url,  userDetail); 

    if (afterSuccess) {
      return afterSuccess.data;
    }
  } catch (error) {
    console.log("error: ", error.response.error);
    if (error.category === 'User Permissions') {
      // forceLogout();
    }
    throw error;
  }
};

-> api-GET

try{
    // console.log("url : ", apiDetail.partnerLocations.url);
let token = sessionStorage.getItem('token');
setHeadersWithUserToken(token);
    let apiResponse = await api.get(apiDetail.partnerLocations.url);
    return apiResponse;
}catch(error){
    console.info('##### demand-response.js:11 #####');
    console.info('========================= Start =========================');
    console.error('error = ', JSON.stringify(error));
    // console.log(error.response.data)
    console.info('========================== End ==========================');
    throw error;
}

-> axios呼叫

   import axios from 'axios';
import { environment } from '../../utils/constants';

let api;
let apiDetail = {
  baseURL: environment.baseURL,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
};
const setAPI = apiDetail => {
  api = axios.create(apiDetail);
};
setAPI(apiDetail);
const setHeadersWithUserToken = token => {
  api.defaults.headers.common['Authorization'] = token;
};
export {
  api,
  setHeadersWithUserToken,
};

图片1 enter image description here 显示控制台错误

图片2 enter image description here 网络通话响应

2 个答案:

答案 0 :(得分:1)

尝试一下

const proxyurl = "https://cors-anywhere.herokuapp.com/"
cosnt url = 'Your URL'
axios.get(proxyurl + url)

我遇到了同样的问题,效果很好。

答案 1 :(得分:1)

将“ proxy”属性(在此处底部)添加到package.json:

"proxy": "http://localhost:<PORT-GOES-HERE>"

现在,不要像这样发出HTTP请求:

axios.get("http://localhost:8080/example")

您应该这样写它们:

axios.get("/example")