【问题标题】:Nesting JSON data to send to API嵌套 JSON 数据以发送到 API
【发布时间】:2021-10-16 22:18:27
【问题描述】:

我有一个 Rails API,我正在尝试以这种格式从反应前端发送 JSON 数据:

{
"user"  : {
             "email": "daves@email.com"
             "password": "dave123"
             "password_confirmation": "dave123"
             "subject": "david"
             "teacher": "student"
             "username": "mikey"
          }
 }

它显然嵌套在“用户”中 但我的代码目前只是在没有用户包裹的情况下发送它,并且 API 不喜欢 JSON 格式

Signup.js:18 POST http://localhost:3001/api/users net::ERR_ABORTED 422 (Unprocessable Entity)


}
email: "daves@email.com"
password: "dave123"
password_confirmation: "dave123"
subject: "david"
teacher: "student"
username: "mikey"
}

如何以正确的格式将 JSON 发送到 API? ,这是登录提交页面的javascript

import React from 'react'
import { useState } from 'react'
//  import axios from 'axios'

export default function Signup() {
  const [teacher, setUserType] = useState("student");
  const [subject, setSubject] = useState(" ");
  const [email, setEmail] = useState("email");
  const [password, setPassword] = useState("password");
  const [password_confirmation, setConfirmedPassword] = useState("confirm password");
  const username = "mikey"

  const handleSubmit = (e) => {
    e.preventDefault();
    const user = {teacher, subject, email, password, password_confirmation, username}
    console.log(user)

    fetch('http://localhost:3001/api/users', {
      mode: 'no-cors',
      method: 'POST', 
      headers: { "Content-Type": "application/json"},
      body: JSON.stringify(user)
    }).then(() => {
      console.log(user)
    })
  }
  
  return (
    <div className="signup-form">
      <form onSubmit={handleSubmit}>
        <label>
          <input 
            type="radio"
            value={teacher}
            onChange={(e) => setUserType(e.target.value)}
            />
            Student
        </label>
        
        <label>
          <input 
            type="radio"
            value={teacher}
            onChange={(e) => setUserType(e.target.value)}
            />
            Tutor
        </label>

        <label>Subject</label>
          <input 
            type="text"
            required
            placeholder=" "
            onChange={(e) => setSubject(e.target.value)}
          /><br/>
        <label>Email address</label>
        <input 
          type="text"
          required
          placeholder="email"
          onChange={(e) => setEmail(e.target.value)}
        /><br/>
        <label>New password</label>
        <input 
          type="text"
          required
          placeholder="choose password"
          onChange={(e) => setPassword(e.target.value)}
        /><br/>
        <label>Confirm password</label>
        <input 
          type="text"
          required
          placeholder="confirm password"
          onChange={(e) => setConfirmedPassword(e.target.value)}
        />
        <button>Submit</button>
      </form>
    </div>
  );
}

谢谢

补充一点,我已经能够在邮递员中提交一个帖子请求,它返回:

{
  "user": {
    "id": 4,
    "email": "testesr@testing.com",
    "username": "fffmike",
    "subject": null,
    "teacher": null,
    "token": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6NCwiZXhwIjoxNjM0MDYxOTkwfQ.8qLlB5wwPGSCsxtkzjuEIxw8PFbLKoM_fo9UllNsonQ"
  }
}

但不是通过获取

【问题讨论】:

  • 关于您的编辑的一个问题:您是说您的 API 响应您的问题似乎与嵌套的 JSON 数据有关吗?这无关紧要;您应该提及您使用 Postman 发送的 请求

标签: javascript ruby-on-rails json api


【解决方案1】:

现在您的user 变量中的用户格式似乎不正确。由于您的user 变量直接作为获取请求的主体传递,因此您需要在运行JSON.stringify 之前创建一个具有所需格式的对象。

const handleSubmit = (e) => {
    e.preventDefault();
    const user = {user: {teacher, subject, email, password, password_confirmation, username}}
    console.log(user)

    fetch('http://localhost:3001/api/users', {
      mode: 'no-cors',
      method: 'POST', 
      headers: { "Content-Type": "application/json"},
      body: JSON.stringify(user)
    }).then(() => {
      console.log(user)
    })
  }

【讨论】:

  • 感谢您的回复。我确实尝试过,但我仍然收到 Signup.js:18 POST localhost:3001/api/users net::ERR_ABORTED 422 (Unprocessable Entity) Signup.js:24 {user: {…}} user: email: "michaelmcloughlin9@gmail.com ” 密码:“michael3214” 密码确认:“michael3214” 主题:“艺术” 老师:“主题” 用户名:“mikey” [[原型]]:对象
【解决方案2】:

尝试使用JSON.stringify({ user }) 而不是JSON.stringify(user) 以创建嵌套字段。

【讨论】:

  • 我已经尝试过了,但仍然 (422 (Unprocessable Entity)) 感谢您的回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2020-04-02
  • 1970-01-01
  • 2023-03-19
  • 2013-05-04
  • 2018-07-12
相关资源
最近更新 更多