has been blocked by CORS policy: Response to preflight request doesn‘t pass access control check: No

作为一个前端,没有后端数据的时候,自己模拟,就是最好的结局,我常用的就是两种:

1.postman进行后端模拟,在此就不进行多余叙述,

2.node后端,用express当中间件,也是问题的源头。

在进行请求时,终端报错为:

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.

我用的编译器是vscode,它的默认编译端口是5500,而我后台路径端口是8089,导致CORS没有通过,也就是跨域问题,直接看代码

let obj = document.getElementById('ref');
    obj.addEventListener('click', ajax)
    // 利用Ajax进行数据请求
    function ajax() {
      console.log('ll');
      let xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            console.log(xhr.responseText);
          } else {
            console.log("Request was unsuccessful" + xhr.status);
          }
        }
      }

      xhr.open("get", "http://127.0.0.1:8089/api/userId", true);

      xhr.send(null)

 后台数据

const exp = require("express");

const app = exp();
app.listen(8089, () => {
  console.log('Server listen http://127.0.0.1:8089')
})
app.use((req, rsp, next) => {
  rsp.setHeader('Access-Control-Allow-Origin', '*')
  next()
})
// app.all(" * ", function(req, res, next) {undefined
//   res.header('Access-Control-Allow-Origin', " * ");
//   res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
//   res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');
//   res.header('X-Powered-By','3.2.1')
//   if(req.method=='OPTIONS') res.send(200);//让options请求快速返回/
//   else next();
//   });


app.get('/api/userId', (req, rsp) => {
  console.log('你请求的地址是/api/hello!', req.name);
  // rsp.send({name:'baobosun',age:47,sex:'男'});
  // rsp.setHeader('Access-Control-Allow-Origin', '*')
  OptMysql(rsp)
  // rsp.send(OptMysql())
})

//做数据库连接
function OptMysql(res) {
  const mysql = require('mysql');
  var par = null
  var connection = mysql.createConnection({
    host: "127.0.0.1",
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'student'
  });
  connection.connect();
  // 查询数据
  connection.query("select * from info", function (err, results, fields) {
    if (err) throw err;
    // console.log('results:', results);
    res.send(results)
  });
}

解决的问题的办法就是在app.use()进行过滤的时候,添加请求头。

rsp.setHeader('Access-Control-Allow-Origin', '*')

猜你喜欢

转载自blog.csdn.net/m0_46833693/article/details/124016734