首页 > 解决方案 > Why doesn't the CORS problem occur on the backend server?

问题描述

I am studying on a toy project using Vue. During development, I made api requests using axios from the front-end and faced a CORS problem. I would really appreciate it if you could give me some information.

Access to XMLHttpRequest at '...' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I know CORS issues are caused by security issues when the requested domain and the responding domain are different. Is that so?

Anyway, I saw the information to enter "Access-Control-Allow-Origin": "*" in the request header, but it didn't work.

So I searched for more information. As a result, I created an express server and configured the proxy for the vue project as shown below.

//vue.config.js
module.exports = {

outputDir:"backend/public",
assetsDir:"assets",
configureWebpack: {
    devtool: 'source-map'
},
devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:3000/api',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    }
}

}

And I just applied the basic example code provided by the api site to the default express environment.

The only thing that changed

  1. Not requested from front-end. (A request was made at back-end (express).)
  2. I used the request module, not axios.

Why doesn't a CORS error occur when I make an api request on back-end (express)?

标签: apiexpressvue.jscors

解决方案


根据 MDN,CORS 是一种为跨域浏览器和服务器之间的请求和数据传输增加安全性的机制,因此它不会受到后端和代理服务器的影响。

现代浏览器在 XMLHttpRequest 或 Fetch 等 API 中使用 CORS 来降低跨域 HTTP 请求的风险。


推荐阅读