Node web server cross-domain pre-request failed, solve!

the rookie wants to build a server with node express, but the cross-domain problem has not been solved. When requesting JSON data, I was at a loss because the pre-request could not pass the permission control and could not complete the cross-domain process.

the following is the front-end request code:

    $.ajax({    
      type: "get",
      dataType: "json",
      url: "http://localhost:8080",
      processData: false,
      contentType: "application/json",
      success: function(res)
      {
        console.log(res);
      }
    });

    let xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost:8080", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
    xhr.onreadystatechange = function()
    {
      console.log(xhr.responseText);
    }

jquery v2.1.4, neither method works, same error message.

this is the configuration of express 4:

app.all("*", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Content-Type", "application/json;charset=utf-8");  
    // if(req.method == "OPTIONS") 
    //     res.send(200);/*options*/
    // else  
    //     next();
});

this is the information in the chrome network request:

General

Request URL: http://localhost:8080/
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

Response Header

Allow: GET,HEAD
Connection: keep-alive
Content-Length: 8
Content-Type: text/html; charset=utf-8
Date: Mon, 16 Apr 2018 04:23:20 GMT
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
X-Powered-By: Express
The OPTIONS request is not allowed in the

header, but it is clearly set in express.

this is an error message:

Failed to load http://localhost:8080/: Response to preflight request doesn"t pass access control check: No "Access-Control-Allow-Origin" header is present on the requested resource. Origin "http://localhost:3000" is therefore not allowed access.

solve the problem, thank you!


try using cors module to solve the problem

var cors = require('cors') ;
app.use(cors(
  {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  }
))
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b322f9-e342.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b322f9-e342.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?