后端设置响应头
express为例
// 全局中间件
app.use((req, res, next) => {
res.header({
// 允许的请求域名
'Access-Control-Allow-Origin': '*',
// 允许的请求方法
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE',
// 允许的请求头
'Access-Control-Allow-Headers': 'Content-Type'
})
next()
})
配置反向代理
正向代理与反向代理的区别
- 开发环境下通过webpack的devServer配置反向代理
- 测试和生产环境下通过node、nginx配置反向代理
module.exports = {
devServer: {
// 告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000
proxy: 'http://localhost:4000'
}
}
module.exports = {
devServer: {
proxy: {
'/api1': {
// e.g请求地址:http://localhost:80/api/user跨域
// 代理后:http://localhost:4000/api/user
target: 'http://localhost:4000',
// websocket
ws: true,
// 将 /api1 改为空字符串
pathRewrite: {'^api1':''},
changeOrigin: true
},
'/api2': {
target: 'http://localhost:5000',
ws: true,
pathRewrite: {'^api2':''},
changeOrigin: true
},
}
}
}
axios请求配置
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // 默认值
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `proxy` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
}
}