简体   繁体   English

从本地主机 Vue 项目调用 api 时出现 NodeJS CORS 错误

[英]NodeJS CORS error when calling api from localhost Vue project

I have a project with a NodeJS/Express backend and a VueJS frontend.我有一个带有 NodeJS/Express 后端和 VueJS 前端的项目。 The problem I am facing is that I constantly get CORS errors:我面临的问题是我不断收到 CORS 错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8080/api/plot.跨域请求被阻止:同源策略不允许读取位于 https://localhost:8080/api/plot 的远程资源。 (Reason: CORS request did not succeed). (原因:CORS 请求没有成功)。

I have added the CORS middelware inside my index.js file of my NodeJS backend:我在 NodeJS 后端的 index.js 文件中添加了 CORS 中间件:

const express = require('express');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method',
  );
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
  res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  next();
});

I also have tried a different approach:我也尝试过不同的方法:

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

In the Vue project I have added the proxy to my vue.config.js file:在 Vue 项目中,我已将代理添加到我的 vue.config.js 文件中:

module.exports = {
  devServer: {
    port: 8080,
    proxy: {
      '^/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        secure: false,
        pathRewrite: { '^/api': '/api' },
        logLevel: 'debug',
      },
    },
  },
};

Then I have changed the URL of my API call to post 8080:然后我将 API 调用的 URL 更改为发布 8080:

import axios from 'axios';

export const addPlot = async (plot) => {
  const url = `https://localhost:8080/api/plot`;
  return await axios.post(url, plot).then((res) => {
    console.log(res);
  });
};

在此处输入图片说明

First, when you are using Webpack Dev server proxy, you don't need to configure Express with any CORS (assuming in production you are going to serve your Vue app build from the same Express server)首先,当您使用 Webpack Dev 服务器代理时,您不需要使用任何 CORS 配置 Express(假设在生产中您将从同一个 Express 服务器为您的 Vue 应用程序构建提供服务)

Reason why you getting CORS errors is that your app is served from http://localhost:8080 (Webpack Dev server) but you are making your Axios request to https://localhost:8080/api/plot - important part is HTTPS:// and because browser is using same-origin policy only if protocol + host + port are all same, browser is firing CORS pre-flight request您收到 CORS 错误的原因是您的应用程序是从http://localhost:8080 (Webpack Dev 服务器)提供的,但是您正在向https://localhost:8080/api/plot发出 Axios 请求 - 重要的部分是HTTPS: //因为浏览器仅在协议 + 主机 + 端口都相同时才使用同源策略,所以浏览器正在触发 CORS 预检请求

Just make your Axios calls to HTTP instead of HTTPS and you should be fine...只需让您的 Axios 调用 HTTP 而不是 HTTPS,您应该没问题...

  1. Make sure you processing preflight request (OPTIONS with empty 204 answer) https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request确保您处理预检请求(带有空 204 答案的选项) https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

  2. Try to add Access-Control-Expose-Headers https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers尝试添加Access-Control-Expose-Headers https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request允许服务器指示哪些响应标头应可用于浏览器中运行的脚本,以响应跨域请求

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

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