【问题标题】:CORS error despite using cors middleware in nodejs api尽管在 nodejs api 中使用了 cors 中间件,但 CORS 错误
【发布时间】:2021-07-25 11:35:33
【问题描述】:

更新 4:当我使用“yarn start”而不是 pm2 运行 Node 应用程序时,我能够加载一个空白数组作为返回而不是 404 Not Found,仍然是 CORS 错误,但没有 404。

更新 3:我不确定返回错误 404 到底是什么。我将服务器应用程序中的所有 404 返回错误都删除为 406,但它仍然在空白白页上显示“404 Not Found”,这意味着它是不是 nginx 返回 404 或者它会这样说。我很困惑X-x

更新 2:我现在在网络选项卡中看到,在 CORS 错误后我收到“404 Not Found”返回,我认为问题可能出在我的 nginx 配置中。我想也许在最后一部分,因为我注意到 Certbot 设置了可能的返回 404,但我似乎找不到为 api url 添加重定向的语法。

map $http_upgrade $connection_upgrade {
    default         upgrade;
    ''              close;
}
server {
     
       server_name example.com www.example.com;
       
    add_header 'Access-Control-Allow-Origin' 'https://example.com';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

       location / {
        # Backend nodejs server
        proxy_pass         http://127.0.0.1:3000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade     $http_upgrade;
        proxy_set_header    Connection  $connection_upgrade;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}

server {

       server_name api.example.com;

    add_header 'Access-Control-Allow-Origin' 'https://api.example.com';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

       location / {
        # Backend nodejs server
        proxy_pass         http://127.0.0.1:5000;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade     $http_upgrade;
        proxy_set_header    Connection  $connection_upgrade;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot



}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


     
       server_name example.com www.example.com;
    listen 80;
    return 404; # managed by Certbot




}

再一次把我的头撞到墙上,试图在 VPS 服务器上设置我的 NodeJS Api 和 React App 前端。

我收到此错误 (index):1 Access to XMLHttpRequest at 'https://api.example.com/questions/getTags' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在我的 NodeJS 应用程序中使用 cors 中间件,并尝试了这里建议的所有解决方案:

CORS express not working predictably

这是我的代码:

import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import questionRoutes from './routes/questions.js';
import userRoutes from './routes/users.js';


const app = express();
dotenv.config();

app.use(express.json({ limit: "30mb", extended: true}));
app.use(express.urlencoded({ limit: "30mb", extended: true}));
app.use(cors());

app.use('/questions', questionRoutes);
app.use('/user', userRoutes);

const CONNECTION_URL = process.env.CONNECTION_URL;
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => app.listen(PORT, () => console.log(`Server Running on port: ${PORT}`)))
    .catch((error) => console.log(error.message));

mongoose.connection
    .once('open', () => console.log('Connected'))
    .on('error', (error)=> {
        console.log("Error: " + error);
    });

mongoose.set('useFindAndModify', false);```

我也尝试像这样将标头添加到我的 nginx 配置中......

        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

但那里也没有骰子。

cors 错误非常无用,因此非常感谢有关从何处开始故障排除的任何建议。

谢谢

更新:这里的请求是我在客户端的 api 调用。

import axios from 'axios';

const API = axios.create({ baseURL: 'https://api.example.com/' });

API.interceptors.request.use((req) => {
    if(localStorage.getItem('profile')) {
        req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).token}`;
    }

    return req;
});

API.interceptors.response.use((res) => {
    return res;
}, err => {
    //console.log(err.response.data.message);
    throw new Error(err.response.data.message);
});

export const fetchQuestions = (tagName) => API.post('/questions', tagName);
export const fetchTags = () => API.get('/questions/getTags');

【问题讨论】:

  • 能否在前端添加API请求代码
  • 添加到帖子@AbuDujanaMahalail
  • 您是否尝试在 cors 中间件中设置原点?喜欢这个 app.use(cors({origin: 'https://example.com'}));
  • @Cavdy 刚试过,没解决

标签: node.js reactjs api nginx


【解决方案1】:

解决方案 1: 您可以尝试在返回响应的块中添加以下标头。,

res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")

解决方案 2: 或者,您可以在 app.jsserver.js 文件中使用以下代码 sn-p 为所有响应添加这些标头。

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next() 
})

【讨论】:

  • 非常感谢您的回复,但这些并没有解决问题:(
【解决方案2】:

在你的 Nginx 配置中,在 proxy_pass 之后的位置...在下面为两台服务器添加这个

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
proxy_cache_bypass $http_upgrade;

【讨论】:

  • 感谢您的回复,但没有工作:(
【解决方案3】:

问题原来是 PM2,而不是 API 或 nginx。

我卸载并重新安装了 PM2,现在它可以工作了:-/

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 2020-11-05
    • 1970-01-01
    • 2020-10-01
    • 2020-11-07
    • 2019-06-11
    • 2020-09-08
    • 2019-09-17
    • 2019-02-22
    相关资源
    最近更新 更多