gpt4 book ai didi

javascript - 如何处理来自服务器的空 json 响应

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:11 25 4
gpt4 key购买 nike

我的前端应用程序中有一个函数调用我的 Node.js 后端服务器:

客户端功能:

  this.geocode = (placeName) => {
const url = '/api/twitter/geocode?' + 'query=' + encodeURIComponent(placeName);
return fetch(url)
.then(processResponse)
.catch(handleError)
}


// API Helper methods
const processResponse = function (response) {
if (response.ok) {
console.log(response);
return response.json()
}
throw response;
}

const handleError = function (error) {
if (error.json) {
error.json().then(error => {
console.error('API Error:', error.message || error)
})
} else {
console.error('API Error:', error.message || error)
}
}

服务器路由:

app.get('/api/twitter/geocode', (req, res) => {
var parameters = {
query: req.query.query
}

Twitter.get('geo/search', parameters)
.then(response => {
console.log("RESPONSE:")
console.log(response);
// check if there is a place for the given query
if(response.date.places.length > 0){
res.send(response.data.result.places[0].bounding_box.coordinates[0][0]);
}
res.send()
})
.catch(e => res.status(500).send('Something broke!')
)
});

placeName 是一个不存在的地点(或者至少 Twitter 不知道)的名称时,就会出现问题。后端的 console.log(response) 向我展示了对 Twitter api 的此类请求会导致返回没有位置数据的消息:

 { data: 
{ result: { places: [] },
query:
{ url: 'https://api.twitter.com/1.1/geo/search.json?query=FOOBARTOWN',
type: 'search',
params: [Object] } },
resp:

/*etc...*/

如您所见,places 是一个空列表。此响应导致我的前端崩溃。我想知道为什么。查看错误信息:

   const handleError = function (error) {
if (error.json) {
> error.json().then(error => {
console.error('API Error:', error.message || error)
})
} else {

以及浏览器中的其他一些控制台输出:

GET http://localhost:3000/api/twitter/geocode?query=FOOBARTOWN 500 (Internal Server Error) (model.js:197)
Uncaught (in promise) SyntaxError: Unexpected token S in JSON at position 0
at handleError (model.js:214)

我们似乎收到了错误 500。但为什么?我的服务器没有出现故障。 Node.js 控制台中没有错误消息。

此外,程序似乎以 handleError 结束,然后无法将错误转换为 json。

  1. 为什么会转到handleError?有什么错误吗?
  2. 为什么显示我的服务器失败(错误 500)?
  3. 如何确保如果 this.geocode 收到空消息,我不会崩溃并返回该空消息(以便我可以检查空消息并在我的 React.js 组件中采取适当的操作)?

最佳答案

Why does it go to handleError? What's the error?

您的服务器正在发送 500 状态代码,并以 Something Broken! 作为响应正文。

当您尝试在非 JSON 字符串上使用 res.json() 时,您会得到:

Uncaught SyntaxError: Unexpected token S in JSON at position 0

if(error.json) 没有按照您的想法进行操作。当 response.ok 为 false 时,handleError 被调用,因为否则您将抛出获取响应对象,在这种情况下,error 参数将是实现 Body 的获取响应,它有一个 json 方法,即使正文不是 JSON(这就是您的情况)。

您的handleError可以这样写,您将在其中处理fetch错误和非2xx响应。

const handleError = async function(error) {

if(error instanceof Response) {

if(error.headers.get('content-type').includes('application/json'))
error = await error.json();
else error = await error.text();

}

console.error('API Error:', error.message || error)
}

Why does it say my server failed (error 500)?

console.log(e) 放在 Twitter.get().catch 上,您就会发现。

<小时/>

您的 Twitter.get().then 也是错误的,因为您发送了两次响应。

if(response.date.places.length > 0){
res.send(response.data.result.places[0].bounding_box.coordinates[0][0]);
}
res.send()

应该是:

 if(response.date.places.length > 0)
return res.send(response/*...*/);

res.send()

关于javascript - 如何处理来自服务器的空 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com