Taylous
Taylous

Reputation: 252

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)?

Upvotes: 1

Views: 2750

Answers (1)

Arman Taherian
Arman Taherian

Reputation: 1092

According to MDN, CORS is a mechanism to add security to requests and data transfers between cross-origin browsers and servers, so it won't affect by back-end and proxy servers.

Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.

Upvotes: 5

Related Questions