2012-11-11 46 views
0

我正在端口8081上運行http服務器,並試圖使用getJSON jQuery函數獲取JSON。但我總是與跨域(CORS)問題運行。我正在考慮使用JSONP,但我不知道我是如何在node.js腳本中實現它的。需要克服跨域問題的幫助,使用服務器端的節點和客戶端的JS使用

headers["Access-Control-Allow-Origin"] = "*"; 
    headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; 
    headers["Access-Control-Allow-Credentials"] = false; 
    headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER"; 
    headers["Access-Control-Max-Age"] = 86400; 
    response.writeHead(200, headers); 
    var objToJson = {"response":res }; 
    response.write(JSON.stringify(objToJson)); 

這是我的客戶端代碼。

jQuery.getJSON('http://localhost:8081', function(data) { 
    console.log(data); 
    }); 
+1

什麼是確切的錯誤信息?在使用CORS時,我發現Chrome的控制檯有最有幫助的錯誤日誌 – guillaume

+0

這是錯誤消息: - XMLHttpRequest無法加載http:// localhost:8081 /。 Access-Control-Allow-Origin不允許源http:// localhost:8080。 – user1386101

回答

0

不知道你做錯了什麼,但我複製你的代碼,填補了空白,它的工作對我來說(在Firefox 16和Chrome 24)。

這裏是我的CORS demo

  • app.js

    var http = require('http'); 
    
    http.createServer(function(request, response) { 
        var headers = {}; 
        headers["Access-Control-Allow-Origin"] = "*"; 
        headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; 
        headers["Access-Control-Allow-Credentials"] = false; 
        headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER"; 
        headers["Access-Control-Max-Age"] = 86400; 
    
        response.writeHead(200, headers); 
        var objToJson = {"response": "hello cors" }; 
        response.write(JSON.stringify(objToJson)); 
        response.end() 
    }).listen(8081) 
    
  • 的index.html

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset=utf-8 /> 
    <title>CORS demo</title> 
    </head> 
    <body> 
        view results in the console 
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
        <script type=text/javascript> 
        jQuery.getJSON('http://localhost:8081', function(data) { 
         console.log(data); 
        }); 
        </script> 
    </body> 
    </html> 
    
1

你能適應這個PHP腳本,邏輯是很簡單。 積分:https://stackoverflow.com/a/1678243

if (array_key_exists('callback', $_GET)) { 
    // JSONP String 
    header('Content-Type: text/javascript; charset=utf8'); 
    header('Access-Control-Allow-Origin: *'); 
    header('Access-Control-Max-Age: 0'); 
    header('Access-Control-Allow-Methods: GET'); 

    $callback = $_GET['callback']; 
    echo $callback . '(' . $data . ');'; 
} else { 
    // JSON String 
    header('Content-Type: application/json; charset=utf8'); 
    echo $data; 
} 
相關問題