Technology Sharing

[CORS error] Cross-domain request problem: CORS solutions in various environments

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

insert image description here

🔥 个人主页:Blank Verse

insert image description here

insert image description here

Cross-origin resource sharingCross-Origin Resource Sharing (CORS) is a common challenge in front-end development. This article will introduce solutions in different environments (such as Vue3 + Vite projects, jQuery projects, and other environments).


1. Common causes of CORS errors

The essence of the cross-domain problem is that the browser restricts loading resources from one source (domain, protocol, port) to another source for security reasons. This security mechanism is called the "same-origin policy". The same-origin policy stipulates that the browser will only allow the request to pass if the requested URL has the same protocol, domain name, and port as the URL of the current web page.

  1. Lack of CORS headers
    The server did not set the correct CORS response headers, causing the browser to reject the request. For example, the browser expects the server to respond withAccess-Control-Allow-Origin header, if it is not set, the browser will block the request.

  2. Cross-origin request prohibited
    By default, browsers block cross-origin requests to protect the user's security. If the server does not allow access to a specific domain, the browser will throw a CORS error.

  3. Preflight request failed
    For some complex requests, the browser will send a preflight request (OPTIONS request) to confirm whether the server allows the request. If the preflight request fails, it will cause a CORS error.


2. Solution

1. Vue3 + Solutions under the Vite project

Through Vite's development server proxy function, local requests can be proxied to different servers to avoid cross-domain issues. The following are the specific steps:

Create a Vue3 + Vite project
npm create vite@latest
cd your-project-name
npm install
  • 1
  • 2
  • 3

Select the Vue3 template and enter the project directory.

Configure Vite's proxy

Found in the root directory of the Vite projectvite.config.ts(orvite.config.js), and configure as follows:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://api.example.com', // 目标服务器
        changeOrigin: true, // 是否改变请求源
        rewrite: (path) => path.replace(/^/api/, ''), // 重写路径
      },
    },
  },
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
send request

In Vue components, you canaxiosorfetchSend a request. For example:

<template>
  <div>
    <button @click="fetchData">获取数据</button>
    <div v-if="data">{{ data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';

export default defineComponent({
  setup() {
    const data = ref(null);

    const fetchData = async () => {
      try {
        const response = await axios.get('/api/data');
        data.value = response.data;
      } catch (error) {
        console.error('请求错误:', error);
      }
    };

    return {
      data,
      fetchData,
    };
  },
});
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

2. Solutions under the jQuery project

In jQuery projects, CORS issues can be resolved by setting request headers or using JSONP.

Using CORS Request Headers

Make sure the server sets the correct CORS headers, such as Access-Control-Allow-OriginWhen the client initiates a request:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $.ajax({
    url: 'http://api.example.com/data',
    method: 'GET',
    success: function(data) {
      console.log(data);
    },
    error: function(xhr, status, error) {
      console.error('请求错误:', error);
    }
  });
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
Using JSONP

If the server supports JSONP, you can solve the cross-domain problem in the following ways:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $.ajax({
    url: 'http://api.example.com/data',
    method: 'GET',
    dataType: 'jsonp', // 使用JSONP
    success: function(data) {
      console.log(data);
    },
    error: function(xhr, status, error) {
      console.error('请求错误:', error);
    }
  });
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3. Solutions in other environments

Using a server-side proxy

In many cases, you can set up a proxy on the server side to forward cross-domain requests through the server side. For example, in Node.js you can usehttp-proxy-middleware

const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://api.example.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api': '',
  },
}));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Setting CORS Headers

Make sure the server response includes the correct CORS headers. For example, in Node.js + Express:

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

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

app.get('/data', (req, res) => {
  res.json({ message: 'Hello World' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
Configure proxy using Nginx

In Nginx, you can solve the CORS problem by configuring the proxy:

server {
    listen 80;
    server_name yourdomain.com;

    location /api/ {
        proxy_pass http://api.example.com/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Conclusion

The CORS problem isFront-end developmentCORS is a common challenge in the web application, but it can be effectively solved through reasonable proxy configuration and server settings. In different environments, you can use Vite's proxy function, set request headers, JSONP, server-side proxy, Nginx proxy and other methods to solve cross-domain problems. I hope this article will help you understand and solve CORS problems.