2

試圖爲客戶端應用程序創建服務器端API。客戶完全是在寫反應。在發展送達webdevserver在端口3000的服務器在端口3001 聽我添加代理到package.json文件中的客戶端應用程序的如下:來自客戶端的代理請求通過create-react-app和webpack dev服務器將應用程序反饋給服務器

{ 
    "name": "client", 
    "version": "0.1.0", 
    "private": true, 
    "devDependencies": { 
    "react-scripts": "0.8.5" 
    }, 
    "dependencies": { 
    "react": "^15.4.2", 
    "react-dom": "^15.4.2", 
    "react-router": "^3.0.2", 
    "superagent": "^3.4.1" 
    }, 
    "scripts": { 
    "start": "react-scripts start", 
    "build": "react-scripts build", 
    "test": "react-scripts test --env=jsdom", 
    "eject": "react-scripts eject" 
    }, 
    "proxy": "http://localhost:3001/" 
} 

但一旦我請求服務器API它失敗:

import Request from 'superagent'; 

export function searchTasks(text, callback) { 
    Request.get('http://localhost:3000/api/v1/tasks', response => { 
    callback(response.body.Search); 
    }) 
} 

響應對象爲空。如果我嘗試使用3001端口請求API - 一切正常。看來web-dev-server沒有代理這些請求,或者,我錯過了一些額外的配置選項?

+0

您是否嘗試執行'/ api/v1/tasks'而不是[docs](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/) template/README.md#proxying-api-requests-in-development)建議?另外,我注意到你正在使用'superagent'而不是'fetch' api - 切換到後者可能會有所幫助。 –

+0

嘗試了不同的網址,但同樣的問題 –

+0

如何將您的'proxy'更改爲'http:// localhost:3001'(丟失最後一個'/')? –

回答

2

這個失敗的原因是因爲您使用superagent來完成您的請求。 superagentcreate-react-app代理髮送錯誤的Accept標頭以正常工作。根據create-react-app documentation中的意見,代理設置使用一些啓發式來處理應發送到歷史記錄API的內容以及應該代理什麼內容。

您可以通過將.accept('json')添加到您的請求中來最輕鬆地解決此問題。這是這樣做的:

import Request from 'superagent'; 

export function searchTasks(text, callback) { 
    Request.get('http://localhost:3000/api/v1/tasks') 
    .accept('json') 
    .end(response => callback(response.body.Search)); 
} 

另一種方法是使用fetch API。您可以在文檔中閱讀關於它的更多信息(以及如何爲較舊的瀏覽器填充它)。

+0

謝謝你的詳細解釋。看來你提供的代碼示例存在一些問題。它不起作用,我不知道爲什麼。它只是返回null作爲迴應。但我明白了,並使用'request' npm包來達到同樣的目的,並且將'Accept'頭改爲'application/json',它工作正常。 –

相關問題