1 跨域問題總概述
跨域指的是从一个域名到另一个域名去请求资源,跨域名请求同源策略,浏览器的安全机制,跨域是浏览器的行为,不是服务器的行为;
简化来讲就是,网页(浏览器)向后台服务器发送一个请求之后,浏览器会拦截这个请求,并检查这个请求是不是跨域访问,如果是跨域访问,便要向服务器端核对,是否允许这个请求进行跨域访问,如果允许,则把请求发送出去,如果不允许,则报错。
所以我们解决这个问题的办法就是,要么在后台加上允许跨域访问的中间件,要么在前台发送请求时,加上允许跨域访问的配置;
2 後台解決 (只需要添加一個中間件就可以),一般情况下,需要对跨域中间件进行相应的配置,只允许特定的请求跨域;
const express = require("express"); const cors = require("cors"); const app = express();
// 这样就允许所有的服务器端的请求进行跨域访问了 app.use(cors()); app.post("/cross-origin", function (req, res) { res.json({ message: "跨域問題解決成功", }); }); app.listen(3000);
3 前台解決 (在vite配置中添加代理配置)
import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { // 这个代理配置的简要意思就是,对target服务器上以api开头的url请求,允许跨域访问; proxy: { // 拦截以api开头的接口地址 "/api": { // 目标服务器 本地服务器向目标服务器发起请求 target: "http://localhost:3000", // 是否开启允许跨域 changeOrigin: true, }, }, }, });
- node vuenode vue ruoyi-vue-activiti node-sass activiti ruoyi node_modules vue-loader modules loader vue-admin-template template admin node vue-admin-template-master vue-cli-service node_modules node homebrew vue-cli macos vue node_global脚本program vue vue-template-compiler前端node_modules 全家node vue js 脚手架node_global vue software