How to solve cross-domain problems when the local development environment built by vite requests a third-party interface

acc693e06fb24b195eaa7458f07e4bbb.png

Preface

In the local development environment built by Vite, how to solve the cross-domain problem when requesting a third-party interface?

In the local development environment, as long as the interface is requested, if there is no proxy configuration, there will be same-origin policy and cross-domain problems. Either proxy locally, proxy on the server, or set the request header to allow cross-domain. Let's do this below. Introducing how to solve the cross-domain problem when the local development environment built by Vite requests a third-party interface.

solution

  1. Configure proxy

Configure the proxy invite.config.js, add theserver object, and configure theproxy proxy, when requesting< in the component /span>When the interface starts with /api, it will be proxied tohttp://v.juhe.cn

import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
  // 解决本地接口请求跨域的问题,配置server
  server: {
    https: false,
    // 是否自动在浏览器打开
    open: true,
    cors: true,
    proxy: {
      '/path': {
        target: 'https://v0.yiketianqi.com',    // 接口域名,接口服务器地止
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/path/, '')
    },
   }
 }
})

In a single-file component, when requesting an interface, the address of the interface starts with /path/, and that’s fine. If you write the complete address, an error will be reported and a cross-domain situation will occur< /span>

import axios from "axios";

async function getWeatherData() {
  try {
       const params = {
              unescape:1,
              version:'v61',
              appid: 69617844,
              appsecret:'Cus4jy7S',
              cityid: this.value
        }
        const response = await this.$axios.get('/path/api',{params});
        console.log(response);  
   catch (error) {
    console.log(error);
   }
}

If you don’t use axios, you can also use fetch, but it needs to be converted

fetch("https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=69617844&appsecret=Cus4jy7S").then(res => {
    res.json().then(json => console.log(json))
})

In terms of PC and mobile compatibility, the returned response body is readable stream, and the request does not include cookie by default. Configuration items need to be added (fetch(url,{credentials:'include'}))If token authority verification is involved, it is not appropriate to use fetch

does not support abort and does not support timeout control. Timeout control implemented using setTimeout and promise.reject cannot prevent The request process continues to run in the background, which will cause traffic congestion

fetchThere is no way to monitor the progress of native requests, but XR can

Excellent score:

  • Syntax simplification, semantics

  • Standard-based promise implementation, supportasync/await

  • Lower level, providing rich API

  • Breaking away from XHR, it is a new implementation method in the ES specification

Notice

It should be noted that in the production environment, the proxy needs to be turned off, otherwise an error will be reported, because in the production environment, the interface server address is different, so the proxy needs to be turned off

In the production environment, the proxy should be implemented inweb the server, which means that back-end students need to provide support

Front-end and back-end development interface joint debugging and docking parameters

2023-09-13

a64c853c6b8f0bb578ba046806c61e1e.jpeg

Fill out questionnaires and earn bonuses

2023-09-12

caf2d73a492e094e386e3cad25f61e8f.jpeg

Implementing 3D panoramic room viewing in Vue

2023-09-11

2be954e391fbc5d411e8fb7460d3842a.jpeg

The old lady, aunt and harvester scholar were banned

2023-09-10

18b115064d5d3ad0a153fdcc6b070767.jpeg

Let’s talk about sauce latte, Ruixing and Moutai join forces

2023-09-09

9e9c49f7e008df42f0a97face533cdd9.jpeg

Implement automatic rotation of 3D ball in Vue

2023-09-08

216dc23967b11b86eb542f43356dd68c.jpeg

0edb3abdd29b17e6bec8418d4bb009fa.png

(Able to draw and answer questions)

a5c55bd58888aea52066323528c701a3.png

Guess you like

Origin blog.csdn.net/wzc_coder/article/details/132960135