简体   繁体   English

firebase POST url 400 错误请求

[英]firebase POST url 400 bad request

I am trying to use a very simple method to post requests to firebase realtime DB from my reactjs app.我正在尝试使用一种非常简单的方法从我的 reactjs 应用程序向 firebase 实时数据库发布请求。 Here is a screenshot of a one entry into my DB .这是一个进入我的数据库的屏幕截图。 Here the first entry under blogs is the UID of the user and that user can create multiple blogs for example with id b1 in the screenshot.这里 blogs 下的第一个条目是用户的 UID,该用户可以创建多个博客,例如屏幕截图中的 id b1。 Friebase DB url 和示例表条目

Here is my code for the POST request:这是我的 POST 请求代码:

const id = localStorage.getItem('uid')
 const postData = async () => {
        var num = localStorage.getItem('blogNumber')
        const resp = await fetch(
            'https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app.firebaseio.com/blogs.json',
            {
             method: 'POST',
             body: {
                id: {
                    num : {
                        title: titleRef.current.value,
                        description: contentRef.current.value,
                        createdAt: new Date(),
                        isPosted: false
                    }
                }
            },
            headers: {
                'Content-Type': 'application/json'
            }
            });
            const data = await resp.json()
           localStorage.setItem('blogNumber', localStorage.getItem('blogNumber') +1)
    }

I get 400 bad request when trying to hit this url尝试点击此网址时收到 400 个错误请求

But according to this page, this seems to be the correct url I am hitting但根据这个页面,这似乎是我正在点击的正确网址

https://retool.com/blog/your-guide-to-crud-in-firebase-realtimedb-with-rest-api/ https://retool.com/blog/your-guide-to-crud-in-firebase-realtimedb-with-rest-api/

There are a number of things wrong here:这里有很多问题:

  • You aren't using the value of id or num here, you need to wrap them in square brackets您没有在这里使用idnum的值,您需要将它们包装在方括号中
  • The body property of a fetch API call should be passed through JSON.stringify . fetch API 调用的body属性应该通过JSON.stringify传递。
  • You shouldn't post a Date object in the body of a request.您不应在请求正文中发布 Date 对象。 Either convert it to a string, convert it to a plain number, use a timestamp object or use a server value placeholder.将其转换为字符串、将其转换为纯数字、使用时间戳对象或使用服务器值占位符。
  • Your code always assumes that the post was created successfully.您的代码始终假定帖子已成功创建。 The fetch API will not throw an error for bad status codes. fetch API 不会因错误的状态代码而引发错误。 You should check the status code to determine what you want to do.您应该检查状态代码以确定您想要做什么。 As Firebase Database operations usually respond in JSON, I've parsed the body here as JSON before checking the code however you should probably check for empty bodies first.由于 Firebase 数据库操作通常以 JSON 响应,因此我在检查代码之前将此处的主体解析为 JSON,但是您可能应该先检查空主体。
  • Using POST /blogs.json will overwrite your entire /blogs tree each time you write data.每次写入数据时,使用POST /blogs.json将覆盖整个/blogs树。 You should change the path or use a PATCH request with the proper body for it.您应该更改路径或使用带有适当正文的 PATCH 请求。
const id = localStorage.getItem('uid')
const postData = async () => {
  const num = localStorage.getItem('blogNumber')
  const reqData = {
    [id]: { // <-- use square brackets for value as key
      [num]: { // <-- use square brackets for value as key
        title: titleRef.current.value,
        description: contentRef.current.value,
        createdAt: Date.now(), // <-- returns milliseconds since epoch
        isPosted: false
      }
    }
  }

  const resp = await fetch(
    'https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app.firebaseio.com/blogs.json',
    {
      method: 'POST',
      body: JSON.stringify(reqData), // you need to stringify this yourself
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );

  
  const data = await resp.json();

  if (!resp.ok) { // fetch API does not throw errors by itself
    const err = new Error('Unexpected status: ' + resp.status);
    err.data = data;
    err.resp = resp;
    throw err;
  }

  localStorage.setItem('blogNumber', localStorage.getItem('blogNumber')+1)
}

Updated to use deeper path:更新为使用更深的路径:

const id = localStorage.getItem('uid')
const postData = async () => {
  const num = localStorage.getItem('blogNumber')
  const reqData = {
    title: titleRef.current.value,
    description: contentRef.current.value,
    createdAt: Date.now(), // <-- returns milliseconds since epoch
    isPosted: false
  }

  const resp = await fetch(
    `https://assignment-c3557-default-rtdb.asia-southeast1.firebasedatabase.app.firebaseio.com/blogs/${uid}/${num}.json`,
    {
      method: 'POST',
      body: JSON.stringify(reqData), // you need to stringify this yourself
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );
  
  const data = await resp.json();

  if (!resp.ok) { // fetch API does not throw errors by itself
    const err = new Error('Unexpected status: ' + resp.status);
    err.data = data;
    err.response = resp;
    throw err;
  }

  localStorage.setItem('blogNumber', localStorage.getItem('blogNumber')+1)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM