api - Why doesn't the CORS problem occur on the backend server?
问题描述
I am studying on a toy project using Vue. During development, I made api requests using axios from the front-end and faced a CORS problem. I would really appreciate it if you could give me some information.
Access to XMLHttpRequest at '...' from origin 'http://localhost:8080' 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.
I know CORS issues are caused by security issues when the requested domain and the responding domain are different. Is that so?
Anyway, I saw the information to enter "Access-Control-Allow-Origin": "*" in the request header, but it didn't work.
So I searched for more information. As a result, I created an express server and configured the proxy for the vue project as shown below.
//vue.config.js
module.exports = {
outputDir:"backend/public",
assetsDir:"assets",
configureWebpack: {
devtool: 'source-map'
},
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
And I just applied the basic example code provided by the api site to the default express environment.
The only thing that changed
- Not requested from front-end. (A request was made at back-end (express).)
- I used the request module, not axios.
Why doesn't a CORS error occur when I make an api request on back-end (express)?
解决方案
根据 MDN,CORS 是一种为跨域浏览器和服务器之间的请求和数据传输增加安全性的机制,因此它不会受到后端和代理服务器的影响。
现代浏览器在 XMLHttpRequest 或 Fetch 等 API 中使用 CORS 来降低跨域 HTTP 请求的风险。
推荐阅读
- git - git 忽略对文件的更改,直到下一次更改
- gradle - 删除 gradle 任务构建依赖项
- spring - Spring Zuul Oauth2 网关/资源服务器
- amazon-web-services - AWS CloudWatch 规则以 AWS 批处理作为目标返回 FailedInvocation
- cplex - 如何在 CPLEX 中定义这种决策变量
- sql-server - 是否可以向收件人发送两个不同的正文并在 sp_send_dbmail 中复制收件人
- extjs - 现代工具包商店加载事件未触发
- python - 基于另一个数组重新排序
- php - Symfony 控制器相同的功能不起作用
- nuget - 在 VSTS 发布期间将 NuGet 包部署到文件夹位置