# 五.配置跨域问题

# 1.安装

package.json

{
  "name": "5.cors",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 2.文件

# 2.1 src/index.js

let xhr = new XMLHttpRequest()

xhr.open("GET", "/api/user", true)

xhr.onload = function() {
  console.log(xhr.response)
}

xhr.send()
1
2
3
4
5
6
7
8
9

# 2.2 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>webpack跨域</title>
  </head>

  <body></body>
</html>
1
2
3
4
5
6
7
8
9
10
11

# 2.3 用 express 写一个服务端

server.js

let express = require("express")

let app = express()

app.get("/user", (req, res) => {
  res.json({ name: "这是我" })
})
app.listen(3000)
1
2
3
4
5
6
7
8

# 3.配置

# 3.1 webpack.config.js

第一种:配置本地代理实现跨域

const path = require("path")
let HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
  mode: "development",
  entry: {
    home: "./src/index.js",
  },
  devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        pathRewrite: { "/api": "" },
      },
    },
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "index.html",
    }),
  ],
}
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

第二种:模拟数据

before(app) {
    app.get("/api/user", (req, res) => {
    res.json({ name: "before" });
    });
}
1
2
3
4
5

第三种:修改 index.js 中请求地址

let xhr = new XMLHttpRequest()

xhr.open("GET", "/user", true)

xhr.onload = function() {
  console.log(xhr.response)
}

xhr.send()
1
2
3
4
5
6
7
8
9

打开http://localhost:3000/