我尝试了开发人员为同一问题提供的所有解决方案。我更新了Vite.config.js文件-
//vite.config.js
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
server: {
proxy: {
'/api': {
target: 'http://localhost:3000/',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, '')
},
cors:false
},
},
define: {
'process.env': {}
}
})
我在两个文件中添加了标题属性-
//Login.vue
const header = {
headers: {
'Authorization': 'Bearer ${accessToken}',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': POST, GET, OPTIONS,
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': no-cors,
'Sec-Fetch-Site': same-site
},
//App.vue
const header = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': no-cors,
'Sec-Fetch-Site': cross-site,
},
但是,当我检查代码并在网络报头属性下看到-
如何更改这些标头属性或任何其他方法来解决这个CORS问题。我只想解决前端的问题。目前,我通过禁用chrome.exe --用户数据-dir=“C://chrome.exe会话”--禁用web安全来运行这个应用程序,但是我想在不禁用安全性的情况下将它运行到所有浏览器。
Get错误-
任何有价值的建议都会对我有很大帮助。提前感谢
发布于 2022-04-05 16:06:39
首先,您不需要“访问控制-.”客户端的标头。这样你就可以移除这些了。您只能在服务器端设置CORS,在您的示例中,这是Vite服务器。
您在Vite服务器上定义了一个代理,但我认为您在那里犯了一个错误。目标必须是实际api服务器的url,例如https://example.com/realApi
。
接下来,在Vue应用程序中,您需要使用Vite开发服务器的本地url调用api,通常使用http://localhost:3000
并使用/api
作为路径。Vite将重写url如下:
http://localhost:3000/api/TheApiYouAreCalling -> https://example.com/realApi/TheApiYouAreCalling
有关选项,请参见vite docs、server.proxy和节点-http-代理文档。
希望这能有所帮助。
编辑:--如果您在生产中需要一个代理,您可以很容易地使用http-代理构建一个node.js代理。下面的代码是一个示例,您的代理位于服务器上的/proxy
。缺点可能是您需要在服务器上运行node.js。下面的示例是使用http,有关https,请参阅http-代理文档。
var http = require("http");
var httpProxy = require("http-proxy");
var proxy = httpProxy.createProxyServer({});
const server = http.createServer(function (req, res) {
if (/^\/proxy\/api/.test(req.url)) {
req.url = req.url.replace(/^\/proxy\/api/, "");
proxy.web(req, res, {
target: "https://example.com/realApi",
changeOrigin: true,
secure: false,
});
} else {
res.writeHead(200, { "Content-Type": "text/plain" });
const response = "Proxy running...";
res.end(response);
}
});
server.listen(8080);
发布于 2022-03-26 13:04:18
你不能解决前端的CORS问题。
https://stackoverflow.com/questions/71618204
复制相似问题