Api GET请求返回一个空响应,但邮递员没有

时间:2020-07-26 18:08:59

标签: json reactjs api fetch

我正在尝试对远程服务器进行api调用,最初,我收到此错误:No 'Access-Control-Allow-Origin' header is present on the requested resource.

我暂时通过在链接之前附加https://cors-anywhere.herokuapp.com链接来解决此错误,或者有时使用Moesif Cors-Any-where chrome扩展名。现在,提取操作将返回200 ok status,但响应为空。

body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"

response: {}
data: undefined

但是,如果我对邮递员运行相同的查询,它将返回预期的响应json对象。我该如何解决?

 const searchFlightData = (to, from, depDate, adults) => {
        fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
            .then(response => {
                if (response.ok) {
                    console.log(response)
                    return response
                }
                else
                    console.log(`Looks like something went wrong. Status: ${response.status}`)
            })
            .then(response => {
                response.json()
                console.log("response: " + JSON.stringify(response))
            })
            .then(data => {
                console.log("data: " + data)
            })
            .catch(error => {
                console.log(error)
            })
}

3 个答案:

答案 0 :(得分:0)

如果要从服务器请求数据,则该数据必须位于同一域中,或者必须设置'Access-Control-Allow-Origin' header。 我不会依靠https://cors-anywhere.herokuapp.com

之类的服务

对于开发,您可以使用proxy server来绕过此限制。 (许多框架已经为此提供了一种解决方案,我不知道您使用的是哪种框架)

答案 1 :(得分:0)

response.json()返回一个承诺,您必须等待解决该承诺。如果您希望链中的下一个then接收到一些东西,则还必须返回一些东西。

类似的东西应该起作用:

 const searchFlightData = (to, from, depDate, adults) => {
        fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
            .then((response) => {
                if (response.ok) {
                    return response
                } else {
                    throw `Looks like something went wrong. Status: ${response.status}`;
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log("data: " + data)
            })
            .catch(error => {
                console.log(error)
            })
}

或您的console.log:

return response.json().then((data) => console.log(data));

答案 2 :(得分:0)

在前端请求中添加一个Header For accept all as following

Axios request header