您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

express使用cros开启跨域访问

彭世瑜 发布时间:2020-04-23 21:50:11 ,浏览量:2

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

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


    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);
        }
    }

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

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.2367s