简易服务端
const express = require('express');
const app = express();
app.get('/api/user', (req, res) => {
res.json({
name: 'hello'
})
});
app.listen(3000);
发送ajax
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/user', true);
xhr.onload = function () {
console.log('xhr.response', xhr.response)
};
xhr.send();
客户端会请求 webpack-dev-server的服务,然后转发到3000
devServer: {
open: true,
proxy: {
'/api': 'http://localhost:3000'//配置了一个代理
}
},
如果接口不以api开头
服务端
const express = require('express');
const app = express();
app.get('/user', (req, res) => {
res.json({
name: 'hello'
})
});
app.listen(3000);
devServer: {
open: true,
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {
'/api': ''
}
}
}
},
1.重写代理到服务器
2.前端模拟数据
devServer: {
//提供的钩子
before(app) {
app.get('/user', (req, res) => {
res.json({
name: 'hello-before'
})
});
}
},
3.有服务端 不用代理来处理 在服务端中启动webpack 端口用服务端端口
yarn add webpack-dev-middleware -D
服务端文件
const express = require('express');
const webpack = require('webpack');
const app = express();
// 中间件
const middle = require('webpack-dev-middleware');
let config = require('./webpack.config.js');
let compiler = webpack(config);
app.use(middle(compiler));
app.get('/user', (req, res) => {
res.json({
name: 'hello'
})
});
app.listen(3000);
网友评论