简体   繁体   English

CORS 错误,尽管在 nodejs api 中使用 cors 中间件

[英]CORS error despite using cors middleware in nodejs api

UPDATE 4: When I run the Node app with "yarn start" instead of pm2 I am able to load a blank array as being returned instead of 404 Not Found, still CORS error, but no 404.更新 4:当我使用“yarn start”而不是 pm2 运行 Node 应用程序时,我能够加载一个空白数组作为返回而不是 404 Not Found,仍然是 CORS 错误,但没有 404。

UPDATE 3: I'm not sure what exactly is returning error 404. I removed all 404 return errors from my server app to be 406 instead and it still says "404 Not Found" on a blank white page, which means it's not nginx returning the 404 or it would say so.更新 3:我不确定返回错误 404 到底是什么。我从服务器应用程序中删除了所有 404 返回错误,改为 406,但它仍然在空白白页上显示“404 Not Found”,这意味着它不是 nginx 返回404 或者它会这么说。 I'm so confused Xx我很困惑xx

UPDATE 2: I am now seeing in the network tab that after the CORS error I am getting "404 Not Found" returned, I think maybe the problem is in my nginx config.更新 2:我现在在网络选项卡中看到,在出现 CORS 错误后,我收到“404 Not Found”返回,我想问题可能出在我的 nginx 配置中。 I think maybe in the last section as I noticed the Certbot setup a possible return 404, but I can't seem to find the syntax to add a redirect for the api url.我想也许在最后一部分,因为我注意到 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




}

Once again banging my head against the wall trying to setup my NodeJS Api with React App frontend on a VPS server.再次将我的头撞到墙上,试图在 VPS 服务器上设置我的 NodeJS Api 和 React App 前端。

I am getting this error (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.我收到此错误(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.

I'm using the cors middleware in my NodeJS app and have tried all the solutions suggested here:我在我的 NodeJS 应用程序中使用 cors 中间件,并尝试了这里建议的所有解决方案:

CORS express not working predictably CORS 快递无法正常工作

Here is my code:这是我的代码:

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);```

I also tried adding the headers to my nginx config like so...我还尝试将标题添加到我的 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';

but no dice there either.但那里也没有骰子。

The cors error is very unhelpful so would really appreciate any advice on where to start troubleshooting. cors 错误非常无用,因此非常感谢有关从何处开始故障排除的任何建议。

Thanks谢谢

UPDATE: as requested here is my api call in the client.更新:这里要求的是我在客户端中的 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');

Solution 1: You can try adding the following headers in the block where you return a response.,解决方案 1:您可以尝试在返回响应的块中添加以下标头。,

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

Solution 2: Or you can add these headers for all your responses by using the following code snippet in your app.js or server.js file.,解决方案 2:或者您可以使用app.jsserver.js文件中的以下代码片段为所有响应添加这些标头。,

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() 
})

In your Nginx config, after proxy_pass in the location... Add this below for both servers在您的 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;

The problem turned out to be PM2, not the API or nginx.问题原来是 PM2,而不是 API 或 nginx。

I uninstalled and reinstalled PM2 and now it works:-/我卸载并重新安装了 PM2,现在它可以工作了:-/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM