express使用cros开启跨域访问

简介: express使用cros开启跨域访问

如果跨域,前端直接请求后端数据会报错

Access to XMLHttpRequest at 'http://127.0.0.1:8080/' 
from origin 'null' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

项目结构

├── index.html

├── index.js
└── package.json

package.json

{
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1"
}
}

index.js

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/', function (req, res) {
res.send("hello")
})

app.listen(8080, function () {
console.log('listening: http://127.0.0.1:8080/')
})

index.html

<script>
var request = new XMLHttpRequest();
request.open('GET', 'http://127.0.0.1:8080', true)
request.send(null)
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
</script>

通过以上代码就可以正常请求获取后台数据了

            </div>
目录
相关文章
|
Web App开发 安全 应用服务中间件
|
5月前
【Express】—Express路由请求
【Express】—Express路由请求
|
前端开发
express使用cros开启跨域访问
express使用cros开启跨域访问
47 0
|
Web App开发 开发框架 缓存
IIS 部署网站对 OPTIONS 请求直接返回 40x 的处理
了解 OPTIONS 请求的基本功能、作用和大概拦截的原因,逐一排查,分别讲解在 asp.net (.net framework 时代)和 asp.net core (.net core/.net 时代) 的处理方式,OPTIONS 请求在不同的浏览器中默认请求行为表现不一致,通过设置 SetPreflightMaxAge (asp.net core 方式)的最大缓存时间,间接的优化...
339 0
IIS 部署网站对 OPTIONS 请求直接返回 40x 的处理
|
存储 JavaScript 安全
Express+FetchAPI 简单实践Cookie
Express+FetchAPI 简单实践Cookie
295 0
|
JavaScript 算法 前端开发
vue本地开启https访问模式
vue本地开启https访问模式
8714 0
|
JSON 前端开发 数据格式
|
JSON 前端开发 数据格式