跨域问题

    技术2025-04-28  22

    node 跨域

    app.use("/",(req,res,next)=>{ res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS'); next() })

    写在 server.js 里面

    前台解决跨域

    module.exports={ devServer:{ open:true,//自动开启 proxy: { '/api': { target: 'http://localhost:3000/', //对应自己的接口 changeOrigin: true, ws: true, pathRewrite: { '^/api': '' }} } } }

    新建vue.config.js 用 /api 代替接口

    使用

    service.request({ url: "/api/reg/reg", method: "post", data:obj }).then((ok) => { resolve(ok) }).catch((err) => { reject(err) })
    **vue-cli http-proxy-middleware 代理跨域
    cli4 相对于之前的cli 少了配置文件的地方

    那么我们就需要自己来进行配置在根路径根路径根路径创建vue.config.js 注意:当我们添加或者修改这个文件时候必须必须必须必须重启服务

    module.exports = { // 基本路径 publicPath: './', //部署应用包时的基本 URL outputDir: 'dist', // 输出文件目录 assetsDir: '',//放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录 runtimeCompiler: false, //是否使用包含运行时编译器的 Vue 构建版本。设置为true可以使用template productionSourceMap: false,//生产环境是否生成 sourceMap 文件 lintOnSave: true, chainWebpack(config) { config.resolve.alias // .set('style', resolve('public/style')) config.output.filename('js/[name].[hash:16].js');//hash值设置 config.output.chunkFilename('js/[id].[hash:16].js'); // config.output.filename('css/[name].[hash:16].css');//hash值设置 }, configureWebpack: () => { }, // css相关配置 css: { // 是否使用css分离插件 ExtractTextPlugin extract: true, // 开启 CSS source maps? sourceMap: false, // css预设器配置项 loaderOptions: {}, // 启用 CSS modules for all css / pre-processor files. modules: false }, parallel: require('os').cpus().length > 1,//是否为 Babel 或 TypeScript 使用 thread-loader // PWA 插件相关配置 // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa pwa: {}, // webpack-dev-server 相关配置 devServer: { open: process.platform === 'darwin', host: '0.0.0.0', port: 8888, https: false, hotOnly: false, // 设置代理 proxy: { '/api': { target: 'http://localhost:3000/', //对应自己的接口 changeOrigin: true, ws: true, pathRewrite: { '^/api': '' } } }, }, // 第三方插件配置 pluginOptions: { // ... } }
    Processed: 0.013, SQL: 9