Vue配置proxy

1/5/2021 VueProxy

# 文章目录

# 后台

const express = require("express");
const app = new express();

app.get("/api/news", (req, res) => {
  // res.setHeader("Access-Control-Allow-Origin", '*')
  // res.setHeader("Access-Control-Allow-Headers", '*') //响应所有请求
  // res.setHeader("Access-Control-Allow-Methods", '*') // 支持头信息自定义
  console.log("请求");
  res.send("Hello World66666!");
});
app.get("/api/person", (req, res) => {
  res.send("me is person");
});

app.get("/get/person", (req, res) => {
  res.send("me is get person");
});
app.get("/book", (req, res) => {
  res.send("me is book");
});
app.get("/books", (req, res) => {
  res.send("me is books");
});

app.listen(3000, () => {
  console.log("Server Start");
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 前台配置 proxy

module.exports = {
  devServer: {
    open: true,
    port: 9997,
    // 代理
    proxy: {
      // 拦截以 /api开头的请求
      "/api": {
        // 要跨域的域名 这里写了target的话,axios的baseURL就要取消掉
        target: "http://localhost:3000",
        // 是否开启跨域
        changeOrigin: true,
      },
      "/get": {
        target: "http://localhost:3000",
        changeOrigin: true,
      },
      "/data": {
        target: "http://localhost:3000",
        changeOrigin: true,
        // 当接口地址里没有 /data开头 但是前端写了/data/来指定使用代理时,这里使用 ^/data::"/" 可以把前端写的 /data 去掉来发送请求,否则发送的请求是 带有 /data的
        pathRewrite: {
          // '^/data': '/data'   // 这种接口配置出来     http://XX.XX.XX.XX:8083/data/login
          "^/data": "/", //这种接口配置出来     http://XX.XX.XX.XX:8083/login
        },
      },
    },
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 请求示例

const { data: news } = await this.$http.get("/api/news");
console.log("news:", news);
this.msg = news;

const apiPerson = await this.$http.get("/api/person");
console.log("apiPerson:", apiPerson);

const getPerson = await this.$http.get("/get/person");
console.log("getPerson:", getPerson);

const book = await this.$http.get("/data/book");
console.log("book: ", book);

const books = await this.$http.get("/data/books");
console.log("books: ", books);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 请求结果

在这里插入图片描述

最后更新于: 2021年9月15日星期三晚上10点10分
Dawn
DDRKirby(ISQ)