2015-12-03 75 views
0

所以我有一個主要問題。我需要從我構建的小型node.js服務器獲取數據,然後使用該數據。我遇到的問題是錯誤說我無法跨域請求,並且從我所看到的我需要爲此添加標頭。我見過很多解決這個問題的例子,但他們都使用快遞。我試圖遠離明確,因爲我在一個沙箱主機,並沒有辦法添加快遞。如何將一個跨域頭添加到node.js響應

--server代碼 -

var http = require('http'), 
    url = require('url'); 
var tweets = {"tweets":[]}; 

http.createServer(function (req, res) { 
    query = url.parse(req.url,true).query; 
    var response = {}; 
    //res.end(JSON.stringify(query)); 
    if(query.action){ 
     console.log("Moving on to phase two!"); 
     if(query.action === "read") { 
      console.log("Listing off the posts"); 
      response = tweets; 
     } 
     else { 
     if(query.action === "post"){ 
      if(query.message) { 
      var tweet = {}; 
      tweet.message = query.message; 
      tweets.tweets.push(tweet); 
      response.stat = "All Good!"; 
      } 
     } 
     } 
    } else { 
     response.error = "No Action"; 
    } 
    response.url = req.url; 
    res.write(JSON.stringify(response)); 
    console.log(JSON.stringify(response)); 
    res.end(); 
}).listen(); 

--client function--

function getJSON(url) { 
     var xhr = new XMLHttpRequest(); 
     xhr.open("GET", url, false); 
     xhr.send(); 
     return JSON.parse(xhr.responseText); 
    } 

我希望這將是一個簡單的辦法,不會是很難做到的。

回答

0

,您將需要在服務器上啓用CORS。

如果使用expressjs,有一箇中間件調用它cors。只需使用app.use(require('cors')),你就會全部設置。

0

您可以使用res.header發送響應返回給客戶端之前設定的CORS頭像下面 -

res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain 
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 

    // Set custom headers for CORS 
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); 

希望它能幫助。

1

我已經想清楚我需要做什麼。我試過跑步

res.setHeader("Access-Control-Allow-Origin", "*"); 

它的工作!除了錯誤,其他方法都沒有做任何其他的方法。謝謝你試圖幫助我回答這個問題。