最近对接一个post请求的接口,postman上可以成功访问,但是在前端代理之后就是浏览器接口就是返回500,如下图:
找了很多办法去解决,这里提供一下思路:
1,传递参数问题,post请求的params参数和data参数是的请求方式是有区别的。(以axios为例)
//params参数
axios({url:'/token',method:'post',params:{key1:value1,key2:value2}}).then(res=>{
console.log(res)
})
//data参数
axios.post('/oauth/token',{key1:value1,key2:value2}).then(res=>{
console.log(res)
})
2,请求头Content-Type的问题
有可能是请求头的Content-Type值与后端写的对不上,需要跟后端沟通。
这里提供一个在网上搜寻到的大佬写的一个在响应头里面查看真实接口访问地址的方法,就是下面的bypass函数,在vite.config.ts文件中添加之后就可以在接口的响应头里面看到了:
server:{
host: true,
proxy:{
'/api':{
target:"你的代理地址",
changeOrigin:true,
rewrite: (p: string) => p.replace(/^\/api/, ''),
bypass(req, res,options){
const proxyUrl = new URL(options.rewrite(req.url) || '', (options.target) as string)?.href || '';
res.setHeader("x-req-proxyUrl",proxyUrl)
}
}
}
}
上述方法都没有解决我的问题,最后找了公司的大佬请教才得知,代理到http和https是不同的,我代理的地址是https,需要有个配置:secure:false!
server:{
host: true,
proxy:{
'/api':{
target:"你的代理地址",
changeOrigin:true,
secure:false,
rewrite: (p: string) => p.replace(/^\/api/, ''),
bypass(req, res,options){
const proxyUrl = new URL(options.rewrite(req.url) || '', (options.target) as string)?.href || '';
res.setHeader("x-req-proxyUrl",proxyUrl)
}
}
}
}
把这个配置加上之后,再重启项目就可以成功访问该接口了!