-1

我有一个 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);
  });
}
4

1 回答 1

0

您可以按如下方式添加“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'

希望这能解决问题。:)

于 2019-09-13T08:24:49.190 回答