【问题标题】:handle post request with redux and rails api使用 redux 和 rails api 处理 post 请求
【发布时间】:2021-04-02 20:21:07
【问题描述】:

我正在尝试在我的 api 中使用 fetch 方法发布一些数据

export const CREATE_MATCH = 'CREATE_MATCH'

export function createMatch(user) {
  const request = fetch("/api/matches", {

    // Adding method type
    method: "POST",


    // Adding headers to the request
    headers: {
        "Content-type": "application/json",
        "X-User-Token": user.authentication_token,
        "X-User-Email": user.email
    }
  })

  return {
    type: CREATE_MATCH,
    payload: request
  }
}

但我只得到响应而不是创建的数据

Response {type: "basic", url: "http://localhost:3000/api/matches", redirected: false, status: 200, ok: true, …}

我不知道如何创建数据。

在 Rails 中,这就是我所拥有的,我在 Match 中没有任何数据,只有 id 和时间戳

def create
  @match = Match.new
  authorize @match
  if @match.save
    render json: @match
  else
    render_error
  end
end

【问题讨论】:

    标签: ruby-on-rails reactjs api redux fetch


    【解决方案1】:

    我刚刚用 async / await 函数找到了答案

    export async function createMatch(user) {
     const request = await fetch("/api/matches", {
    
       // Adding method type
       method: "POST",
    
       // Adding body or contents to send
       // body: JSON.stringify(),
    
       // Adding headers to the request
       headers: {
           "Content-type": "application/json",
           "X-User-Token": user.authentication_token,
           "X-User-Email": user.email
       }
     })
     const match = await request.json();
     console.log(match)
    
     return {
       type: CREATE_MATCH,
       payload: match
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2016-09-29
      • 2019-03-05
      • 2018-05-12
      • 2012-03-14
      • 2021-06-30
      相关资源
      最近更新 更多