简体   繁体   English

TypeError:通过axios发送post请求时将循环结构转换为JSON

[英]TypeError: Converting circular structure to JSON when sending a post request through axios

Im getting this error when I send a post request to the server when the role for the user is seller for which there are 2 extra properties for the JSON : resName and resAddress .当用户的roleseller时,当我向服务器发送发布请求时出现此错误,其中 JSON 有 2 个额外属性: resNameresAddress I am also using placeautocomplete (from google) to get the address of the restaurant (the name of it can be anything for the time being).我也在使用placeautocomplete(来自google)来获取餐厅的地址(它的名字暂时可以是任何东西)。 Register.js:注册.js:

import logo from './logo.svg';
import './App.css';
import React, { Component, useEffect } from 'react';
import { useState } from 'react';
import axios from 'axios';
import LocationSearchInput from './placeComplete';



function Register() {

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("seller");
  const [resName, setResName] = useState("");
  const [resAddress, setResAddress] = useState(React.createRef());


  async function registerUser(e){
    e.preventDefault();
    if (role === 'seller'){     
      const restaurantAddress = resAddress.current
      console.log(restaurantAddress.state.address, resName)
    }
      const response = await axios.post('/api/users/register', 
        {
          name,
          email,
          password,
          resName,
          resAddress,
          role
        }
      ).then(
        res => {
          console.log(res.data)
        }
      )
  }


  function registerRestaurant(){
    if (role === 'seller'){
      return(
        <div>
          <h4>Restaurant Name:</h4> <br />
          <input type='text' 
            placeholder='Restaurant Name'
            value={resName}
            onChange={(e) => setResName(e.target.value)}
          />
          <br />
          <LocationSearchInput ref={resAddress} />
        </div>
      );
    } 
  }

  return (
    <div>
      <form onSubmit={registerUser}>
        <input type="name" placeholder="Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

        <br />

        <input type="email" placeholder="Email" 
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <br />


        <input type="password" placeholder="Password" 
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <br />


        <input type='radio' value='customer' 
          checked={role === 'customer'}
          onChange={(e) => {
            setRole(e.target.value)
          }}
        />
        customer
        <br />

        <input type='radio' value='seller' 
          checked={role === 'seller'}
          onChange={(e) => {
            setRole(e.target.value)
          }}
        />
        seller
        <br />

        {registerRestaurant()}

        <input type='submit' value='Register' />
      </form>
    </div>
  );
}

export default Register;

placeComplete.js: placeComplete.js:

import React from 'react';
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng,
} from 'react-places-autocomplete';
 
class LocationSearchInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = { address: '' };
  }
 
  handleChange = address => {
    this.setState({ address });
  };
 
  handleSelect = address => {
    geocodeByAddress(address)
      .then(results => getLatLng(results[0]))
      .then(latLng => console.log('Success', latLng))
      .then(this.setState({address: address}))
      .catch(error => console.error('Error', error));
  };
 
  render() {
    return (
      <PlacesAutocomplete
        value={this.state.address}
        onChange={this.handleChange}
        onSelect={this.handleSelect}
      >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div>
            <input
              {...getInputProps({
                placeholder: 'Search Places ...',
                className: 'location-search-input',
              })}
            />
            <div className="autocomplete-dropdown-container">
              {loading && <div>Loading...</div>}
              {suggestions.map(suggestion => {
                const className = suggestion.active
                  ? 'suggestion-item--active'
                  : 'suggestion-item';
                // inline style for demonstration purpose
                const style = suggestion.active
                  ? { backgroundColor: '#fafafa', cursor: 'pointer' }
                  : { backgroundColor: '#ffffff', cursor: 'pointer' };
                return (
                  <div
                    {...getSuggestionItemProps(suggestion, {
                      className,
                      style,
                    })}
                  >
                    <span>{suggestion.description}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
    );
  }
}

export default LocationSearchInput;

I am also getting the following warning when I start typing in resAddress:当我开始输入 resAddress 时,我也会收到以下警告:

react_devtools_backend.js:4026 Warning: Each child in a list should have a unique "key" prop. Check the render method of `PlacesAutocomplete`. See https://reactjs.org/link/warning-keys for more information.

Mind you the server is accepting requests through postman.请注意,服务器正在通过邮递员接受请求。

This error usually gets thrown if you're not sending proper JSON.如果您没有发送正确的 JSON,通常会引发此错误。 Your problem seems to happen here:您的问题似乎发生在这里:

const response = await axios.post('/api/users/register', 
        {
          name,
          email,
          password,
          resName,
          resAddress,
          role
        }
      ).then(
        res => {
          console.log(res.data)
        }
      )

Since resAddress is a ref (not proper JSON):由于resAddress是一个ref (不是正确的 JSON):

const [resAddress, setResAddress] = useState(React.createRef());

Change to something like this and you should be fine:改成这样,你应该没问题:

{
  /* ... */
  resAddress: resAddress.current.state.address
  /* ... */
}

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

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