2017-09-24 72 views
5

我想向不受我控制的外部API發出GET請求。由於API的安全性,我的反應應用程序無法直接向端點發出ajax請求。因此,我想創建一個簡單的代理作爲證明here如何在React/Webpack中創建代理以調用外部API

package.json file看起來是這樣的:

{ 
    "name": "my-stack", 
    "version": "0.1.0", 
    "private": true, 
    "dependencies": { 
    "react": "^15.6.1", 
    "react-dom": "^15.6.1", 
    "react-router-dom": "^4.2.2", 
    "react-scripts": "1.0.13" 
    }, 
    "scripts": { 
    "start": "react-scripts start", 
    "build": "react-scripts build", 
    "test": "react-scripts test --env=jsdom", 
    "eject": "react-scripts eject" 
    }, 
    "proxy": { 
    "https://gold-feed.com/paid/*": { 
     "target": "https://gold-feed.com/paid", 
     "changeOrigin": true 
    } 
    } 
} 

然後我的Ajax請求是這樣的:

const apiUrl = 'https://gold-feed.com/paid/<apiID>/all_metals_json_usd.php'; 

jQuery.ajax({ 
    method: 'GET', 
    url: apiUrl, 
    success: (item) => { 
    this.props.addItem(item); 
    } 
}); 

但它不」 t似乎在做任何事情。我還發現了以下錯誤:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

我基本上是有相同的問題記錄在案here,他試圖創建一個代理來訪問蒸汽API。

只是一個側面說明,我相信我正在使用的create-react-app項目是從webpack中捎帶出來的。

+0

非常有趣您的問題,我不是React的專家,但是,似乎沒有代理配置,瀏覽器正在執行請求,當然,CORS策略已應用。自己完成的方法應該是,在節點中公開Rest API,並將後端作爲api的請求者,並且我的前端只與後端進行通信,因此前端不關心CORS第三方apis問題。在react/redux體系結構中使用axios可能會解決問題,但我並不確定 – Kalamarico

+0

我遇到了同樣的問題,但我只是通過執行「proxy」來修復它: 「https:// gold- feed.com/paid/「}'''。你能試試嗎? –

+0

我會嘗試。你把它放在package.json中? – reknirt

回答

1

你可能想出來的,但現在別人這裏是 什麼工作我:

"proxy": { 
    "/proxy": { 
     "target": "https://mybackend.com", 
     "pathRewrite": {"^/proxy" : ""}, 
    "changeOrigin": true 
} 

所以myreact.com/proxy/my/path被重定向到mybackend.com/my/path

我覺得你的情況的錯誤是,你把目標作爲您的代理的關鍵字而不是您的反應服務器上的路徑。