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

As a front-end, when there is no back-end data, it is the best ending to simulate by yourself. I usually use two types:

1. Postman performs back-end simulation, so there is no redundant description here.

2. Node backend, using express as middleware, is also the source of the problem.

When making a request, the terminal reported an error as:

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.

The compiler I use is vscode, its default compilation port is 5500, and my background path port is 8089, which causes CORS to fail, that is, a cross-domain problem, look at the code directly

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)

 Background data

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

The solution to the problem is to add a request header when app.use() filters.

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

Guess you like

Origin blog.csdn.net/m0_46833693/article/details/124016734