webpack 跨域

设置一个服务,由于webpack-dev-server内含express

express

server.js

// express

let express = require('express')

let app = express();

app.get('/api/user', (res) => {
    res.json({name: 'mayufo'})
})

app.listen(3000)   // 服务端口在3000

写完后记得node server.js

访问 http://localhost:3000/api/user 可见内容

index.js

// 发送一个请求
let xhr = new XMLHttpRequest();

// 默认访问 http://localhost:8080  webpack-dev-server 的服务 再转发给3000
xhr.open('GET', '/api/user', true);

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

xhr.send();

webpack.config.js

devServer: {
  proxy: {
      '/api': 'http://localhost:3000' // 配置一个代理
  }
},

results matching ""

    No results matching ""