首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(response.ok === false) {setError(‘response.ok’)

(response.ok === false) {setError(‘response.ok’)
EN

Stack Overflow用户
提问于 2021-03-26 02:22:40
回答 2查看 337关注 0票数 0

在文本区域中键入少于5个字符时,我收到400个错误请求。并且当用户输入太短的文本消息时,我试图向他/她显示错误消息。但是消息不会显示出来。

代码语言:javascript
复制
    const handleFormSubmit = (e) => {
    e.preventDefault()

    const options = {
        method: 'POST',
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify({ message: newThought })
      }

    fetch(HAPPY_THOUGHTS_URL, options)
      .then(response => response.json())
      .then((response => {
        if (response.ok === false) { 
          setError('show')
        } else { 
          fetchThoughtsList()
        }
      })) 
      .catch(error => console.error(error))
  } 

......

  return (
   <div> 
     {error === 'show' && 
        <ErrorPopup
          message="Oops, your message needs to be more than 4 characters. Please give it one more try!" 
          setError={setError} 
        />
      }
    </div>
  )
EN

回答 2

Stack Overflow用户

发布于 2021-03-26 03:20:41

事件的顺序有一个问题,在你的第一个then中,你可以读取ok字段,但在第二个中,只有你调用json获得的数据。试试像这样的东西

代码语言:javascript
复制
 fetch(HAPPY_THOUGHTS_URL, options)
.then(response => {
    if (!response.ok) { 
      setError('show');
      return null;
    } 
    return response.json();
   }) 
  .then(response => {
    if (response) {
      fetchThoughtsList()
    }
  })
  .catch(error => console.error(error))

我假设您只是没有包括处理响应数据的部分,但是如果您真的什么都不做,那么就不需要response.json()和第二个then

代码语言:javascript
复制
 fetch(HAPPY_THOUGHTS_URL, options)
 .then(response => {
    if (response.ok) { 
      fetchThoughtsList()
    } 
    else{ 
      setError('show');
    }
  })
  .catch(error => console.error(error))

尝试将.then(response => {console.log('actual ok value',response.ok); return response}作为第一个then插入,看看它打印了什么,也许响应确实是ok

票数 0
EN

Stack Overflow用户

发布于 2021-03-26 23:40:48

代码语言:javascript
复制
fetch(API_URL, options)
    .then(response => {
      if (!response.ok) {
        setError(true)
        throw new Error ('Ups, something went wrong')
      } else { 
        setNewThought('')
        return response.json()
      }
    })
    .then(recievedThought => setThoughtsList([recievedThought, ...thoughtsList]))
    .catch(err => console.error(err))
  } 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66805483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档