2016-04-29 49 views
0

我正在使用Node,Express和Webpack編寫React應用程序。我的問題是我的API調用的URL總是在主機和路徑之間有一個端口號。似乎關於此主題的大多數問題都與路由有關,而不是外部API調用。從節點HTTP請求中刪除端口號至外部API

我對Request更加舒服,但是我非常沮喪地試圖讓它與Webpack很好地搭配,所以我轉向了Node,我不太瞭解的http。

這裏是負責API調用的方法:

getData() { 
    const self = this; 

    const url = "api.civicapps.org"; 

    const options = { 
     "method": "GET", 
     "mode": "no-cors", 
     "host": url, 
     "path": "/restaurant-inspections/?restaurant_name=" + this.state.nameQuery, 
     "port": 8080, 
     "headers": { 
      "Access-Control-Allow-Origin": "http://localhost:3000" 
     } 
    } 

    const p1 = new Promise(function(resolve, reject) { 
     resolve(
      http.request(options, function(res) { 
       res.setEncoding('utf8'); 
       const body = {}; 

       //This is clearly not ideal, but all I need right now is to get a response from the API 

       res.on('data', function(chunk) { 
        body.push(chunk); 
       }); 
       return body; 
      }).end() 
     ) 
    }); 

    p1.then(function(data) { 
      console.log(data); 

     self.setState({ 
      name: data.body 
     }); 
    }); 

    p1.catch(function(err) { 

     ... 
    }); 
} 

所有我想要做的是一個簡單的測試GET請求,這個API。一旦這個工作,我會沒事的。

在此先感謝。

+0

你指的是什麼端口?你在請求中包含一個端口('8080')。 – WiredPrairie

回答

0

事實證明,將端口設置爲80,並使用sudo運行解決了問題。