vue.config.js中配置跨域,有两种请求地址,怎么配置
时间: 2024-06-10 11:05:57 浏览: 233
您可以在vue.config.js文件中添加以下代码来配置跨域请求地址:
```
module.exports = {
devServer: {
proxy: {
'/api1': {
target: 'http://localhost:3000/',
changeOrigin: true,
pathRewrite: {
'^/api1': ''
}
},
'/api2': {
target: 'http://localhost:4000/',
changeOrigin: true,
pathRewrite: {
'^/api2': ''
}
}
}
}
}
```
在上面的代码中,'/api1'和'/api2'表示你要进行跨域请求的路径,'http://localhost:3000/'和'http://localhost:4000/'分别表示你需要跨域访问的服务器地址。changeOrigin为true表示跨域请求时会处理跨域请求头,pathRewrite用于重写请求路径。
相关问题
vue.config.js 如何配置跨域
可以在 `vue.config.js` 中配置跨域的方法有两种:
1. 使用 `devServer.proxy` 选项。比如:
```
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://your.api.server.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
```
这样,当请求的 URL 以 `/api` 开头时,请求会被代理到 `http://your.api.server.com`,并且带上跨域相关的 header。
2. 使用 `axios` 和 `CORS`(Cross-Origin Resource Sharing)。比如:
```
const axios = require('axios')
module.exports = {
devServer: {
before(app) {
app.get('/api/*', (req, res) => {
let url = 'http://your.api.server.com' + req.url.replace('/api', '')
axios.get(url)
.then(response => {
res.json(response.data)
})
.catch(error => {
res.json(error.response.data)
})
})
}
}
}
```
这样,所有以 `/api` 开头的请求都会被代理到 `http://your.api.server.com`,并且可以避免 CORS 问题。
vue.config.js引入js
### 在 `vue.config.js` 中引入外部 JS 文件
为了在 Vue CLI 3 的项目中通过 `vue.config.js` 正确配置并引入外部 JavaScript 文件,可以采用如下方法:
可以在 `vue.config.js` 使用 Webpack 提供的 `externals` 字段来排除某些包被打包到 bundle 中,并假设这些包已经在运行环境中可用。对于直接引入外部 JS 文件的需求,通常是在构建过程中将其复制到最终输出目录下或是作为资源文件处理。
另一种常见的方式是利用 Node.js 的模块机制,在 `vue.config.js` 中通过 `require()` 或者 ES Module 的导入语法 (`import`) 来加载本地文件系统中的 JavaScript 脚本[^2]。
下面是一个具体的例子展示如何实现这一点:
```javascript
// vue.config.js
const externalJs = require('./path/to/your/externalFile');
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
'window.ExternalLib': 'external-js' // 将外部库挂载至 window 对象以便全局访问
})
]
},
chainWebpack: config => {
config.plugin('copy').tap(() => [{
from: './src/assets/js',
to: 'assets/js'
}]);
}
};
```
上述代码片段展示了两种不同的策略:一是借助 Webpack 插件将特定变量映射为全局对象;二是使用 CopyWebpackPlugin 复制指定路径下的静态资源文件夹到打包后的 dist 目录内[^4]。
需要注意的是,当涉及到跨域请求或其他复杂的服务器端逻辑时,可能还需要调整开发服务器的相关设置,比如代理规则等。
阅读全文
相关推荐















