webpack解决跨域问题
时间: 2023-12-06 19:38:37 浏览: 86
解决跨域的问题
webpack解决跨域问题的三种方式如下:
1. 使用代理:在webpack的配置文件中配置devServer.proxy,将请求代理到目标服务器上,从而解决跨域问题。示例代码如下:
```javascript
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', pathRewrite: {'^/api' : ''}
}
}
}
```
2. 模拟数据:在本地模拟数据,避免跨域请求。可以使用webpack-dev-middleware和webpack-hot-middleware来实现。示例代码如下:
```javascript
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config.js');
const app = express();
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
```
3. 前端启动到服务端上:将前端代码和后端代码部署在同一个服务器上,避免跨域请求。示例代码如下:
```javascript
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/api', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
```
阅读全文