[vue] vite搭建的vue项目跨域二三讲

1. 申明一点, 前端是无法完全解决跨域问题的, 只能暂时性的解决, 所有跨域都需要涉及后端操作,因为打包之后, 所有配置的proxy都会失效

2. vite vue 配置跨域如下

// vite.config.js  ==> defineConfig 配置里面

server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:5000',
        secure: false,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }

3. 本地请求

<template>
  <div>
    <el-button type="primary" @click="test">hello world</el-button>
  </div>
</template>

<script setup>
import axios from "axios";

const test = async () => {
  const resp = await axios.get("/api/test");
  console.log(resp.data);
};
</script>

<style lang="scss" scoped></style>

4. 请求结果

没有写前缀, 默认请求的是和npm run dev 相同的域名, 但是返回的是 代理前缀的结果

5. 服务器代码 python

from flask import Flask, jsonify
# from flask_cors import CORS

app = Flask(__name__)
# CORS(app)


@app.route('/test', methods=['GET'])
def test():
    lis = [
        {"id": 1, "name": "苹果"},
        {"id": 2, "name": "橘子"},
        {"id": 3, "name": "香蕉"},
        {"id": 4, "name": "菠萝"}
    ]
    return jsonify(lis)


if __name__ == '__main__':
    app.run(debug=True)

 

posted @ 2024-12-18 10:43  深海里的星星i  阅读(183)  评论(0)    收藏  举报