鍍金池/ 問(wèn)答/人工智能  HTML5  HTML/ node web服務(wù)端跨域預(yù)請(qǐng)求未通過(guò),求解!

node web服務(wù)端跨域預(yù)請(qǐng)求未通過(guò),求解!

菜鳥(niǎo)想用 node express 搭一個(gè)服務(wù)端,跨域問(wèn)題一直沒(méi)能解決。在請(qǐng)求JSON數(shù)據(jù)的時(shí)候,預(yù)請(qǐng)求始終無(wú)法通過(guò)權(quán)限控制,無(wú)法完成跨域過(guò)程,搞得我不知所措。

以下是前端請(qǐng)求代碼:

    $.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,兩種方法都不行,同樣的錯(cuò)誤信息。

這是 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請(qǐng)求快速返回*/
    // else  
    //     next();
});

這是chrome網(wǎng)絡(luò)請(qǐng)求里的信息:

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

報(bào)頭中沒(méi)有允許 OPTIONS 請(qǐng)求,可在 express 中明明設(shè)置了。

這是報(bào)錯(cuò)信息:

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.

求解惑,謝謝!

回答
編輯回答
空痕

使用cors模塊解決試試

var cors = require('cors') ;
app.use(cors(
  {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  }
))
2018年3月24日 05:10