使用redux和rails API处理post请求

u59ebvdq  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(91)

我正尝试在我的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
  }
}

字符串
但我只得到响应而不是创建的数据
响应{type:“basic”,url:“http://localhost:3000/api/matches”,重定向:false,状态:200,ok:true,...}
我不知道如何创建数据。
在rails中,这是我所拥有的,我没有任何数据在一个Match中,只有id和时间戳。

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

hs1ihplo

hs1ihplo1#

我刚刚用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
 }
}

字符串

相关问题