【问题标题】:Issue with Chrome CORS policyChrome CORS 政策问题
【发布时间】:2020-01-15 01:57:04
【问题描述】:

我有一个 API 可以登录我的系统,但是当使用 axios 发送请求时,它会收到一个 CORS 错误。

我尝试安装 CORS 扩展并重新加载了很多时间,但仍然无法正常工作。

然后我尝试通过 https://cors-anywhere.herokuapp.com/ 发送请求,我收到错误 503 (服务不可用)。

这是我的功能:

function getAccessToken (success, failure){
  axios.request({
    url: `${BaseConstants.REST_BASE_PATH}/rest/auth/login`,
    //`https://cors-anywhere.herokuapp.com/${BaseConstants.REST_BASE_PATH}/rest/auth/login`,
    method: "POST",
    headers: {
      Authorization: 'Basic YWRtaW51c2VyOnBhc3N3b3Jk',
      'Content-type': 'application/json',
      // 'Origin': '*',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Allow-Origin': '*',
    }
  }).then(r => {
    success(r.data);
  }.catch(r => { 
    failure(r.message);
  });
}

【问题讨论】:

  • 你添加了 cors 头“access-control-allow-origin”

标签: reactjs google-chrome cors axios


【解决方案1】:

您可以按如下方式添加“cors”包(快速服务器),也可以在“服务器端”添加特定行以绕过 CORS 问题。

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());

// some route controllers
const customRoute = require('./customRoute.controller');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// Custom routes
app.use('/api/tags', customRoute);

app.use(express.static(path.join(__dirname, 'dist')));


// Catch all other routes & return index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

module.exports = app;

OR

'Access-Control-Allow-Methods': 'GET, POST PUT, DELETE, OPTIONS'
'Access-Control-Allow-Origin': '*'
'Access-Control-Allow-Credentials': ' true'

希望这能解决问题。 :)

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2021-06-24
    • 1970-01-01
    • 2014-05-03
    • 2021-12-07
    • 2020-07-28
    • 2022-01-20
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多