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 r...
如果跨域,前端直接请求后端数据会报错
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.
- 1
- 2
- 3
项目结构
├── index.html
├── index.js
└── package.json
- 1
- 2
- 3
package.json
{
"dependencies": { "cors": "^2.8.5", "express": "^4.17.1"
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
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/')
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
通过以上代码就可以正常请求获取后台数据了
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/105718270
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)