如果跨域,前端直接请求后端数据会报错
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>
通过以上代码就可以正常请求获取后台数据了