1、使用了统一封装的userFetch调用给后端接口的时候报跨域错误
Access to fetch at 'http://localhost:8286/siteweb/captcha/get' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
2、解决方式
参考文章:
https://juejin.cn/post/7200762602805051451
由于我nuxt版本是3.6
所以我是在nuxt.config.js中添加了以下的配置
nitro: {
devProxy: {
"/siteweb": {
target: "http://localhost:8287/siteweb", // 这里是接口地址
changeOrigin: true,
prependPath: true,
}
}
}
3、后端的访问也需要改一下。
因为我的这个nuxt功能使用的是默认的端口:3000
所以我访问的后端的端口地址要改成: http://localhost:3000/siteweb/captcha/get
这里我如果不做转发,直接访问后端的话,端口是用的8287,因为要用这个转发,所以端口也要改成3000。总之要改成nuxt服务的端口。
这样的话当我们访问/siteweb/相关的url时,是会转发到我们的后端的。也避免了跨域问题