SoFunction
Updated on 2025-03-09

Introduction to several commonly used cross-domain processing methods for vue

Setting up Express proxy requests

Based onvue-cliIn the project, set up a proxy in the development environment configuration (config/) to enable all/apidomainAll requests at the beginning are passednpm run devStartedexpressServer redirects to target interface

Official Documentation:/webpack/

proxyTable: {
  '/apidomain':{
  target:'http://localhost:prot',//or ip or domain name.  changeOrigin:true,
  pathRewrite: {
   '^/apidomain': ''
  }
  }
 },

To access h5 on the LAN via IP, add it when starting the development serverhostJust parameters

The dev command is configured as follows

"dev": "webpack-dev-server --inline --progress --config build/ --host 0.0.0.0",

Turn off Chrome security policy to implement cross-domain

Create a new bat file in Windows and paste the following command to open this mode

cd "C:\Program Files (x86)\Google\Chrome\Application" 
 --disable-web-security --user-data-dir=c:/CorsUserData

CoRS cross-domain settings of core server

Official Documentation:/zh-cn/aspnet/core/security/cors

In the actual setting, the header parameter is added on the h5 side.Pre-inspection (OPTIONS) requestAfter reading the above article, modify the general parameters into the query parameters

1. Add cors service

public void ConfigureServices(IServiceCollection services)
{
 //If there are only some interfaces, define one or more named CORS policies, and then select the policy at runtime by name, and use feature tags to set cross-domain. See the document for details ();
}

2. Enable middleware

//Read the domain names that are allowed to cross-domain set in the configuration file. CorsOrigins is an array. Setting ["*"] will allow allvar origins = ("CorsOrigins").GetChildren().Select(s => ).ToArray();
(e =>
{
 (origins).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
//Getting of Configuration object in Startup filepublic IConfiguration Configuration { get; }
public Startup()
{
 var builder = new ConfigurationBuilder()//...AddJsonFile($"");
 Configuration = ();
}

JSONP

JSONP only supports GET requests, CORS supports all types of HTTP requests. The advantage of JSONP is that it supports old-fashioned browsers and can request data from websites that do not support CORS.