Vue-cli 配置代理服务器

376 阅读1分钟

基础知识

  • Ajax

  • 同源策略

  • vue 相关知识

  • vue-cli 相关知识

  • node.js npm Express框架

    • 了解即可,相关代码附有说明

配置代理服务器

目的

  • 解决:浏览器基于Ajax技术向服务端发送请求时

    由于 同源策略 的限制导致无法显示响应内容的问题

思路

  • 由于,同源策略的限制范围是:浏览器基于Ajax技术向服务发送请求,

    对服务器之间的通信没有限制。

    因此,设置一个与客户端同源的代理服务器进行请求的转发进而实现Ajax请求跨域的需求

实践步骤

1. 配置vue.config.js

module.exports = {
  lintOnSave: false,
  // 配置代理服务器
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        pathRewrite: { '^/api': '' }  //重点:重写资源访问路径,避免转发请求 404问题
        // ws: true, //websokect配置 ,默认true
        // changeOrigin: true //设置请求头中的 Host字段
      }
    }
  }
}

2. 代码

服务端(node.js Express框架)

const express = require('express')
const app = express()
// 设置监听端口号
const port = 5000//设置get请求
app.get('/users', (req, res) => {
  res.send('我是5000服务!')
})
​
app.get('/helloWorld', (req, res) => {
  res.send('我是5000服务!')
})
​
​
app.listen(port, () => {
  console.log(`服务端监听到了: http://localhost:${port}`)
})
​
客户端(浏览器)
// 引入 axios
import axios from "axios";
export default {
  name: "Search",
  data() {
    return {
      userName: "",
    };
  },
  methods: {
    doSearch() {
      axios({
        method: "get",
        url: "http://localhost:8080/api/helloWorld",
      }).then(function (response) {
        console.log("服务端返回值:" ,response);
      });
    },
  },
};

总结

vue.config.js

  • pathRewrite 必须配置 否则极易出现 404 问题