我想使用一些 json 服务器模拟数据来测试我的登录应用程序

问题描述 投票:0回答:2

当我使用这个获取函数并在我的表单上测试它时,会创建一个只有 id 的新对象,并且我得到 201 状态而不是 200

export function PostData(userData){
let url = 'http://localhost:3001/users';

return new Promise((resolve, reject) => {
    fetch(url,{
        method: 'POST',
        body: JSON.stringify(userData)
    })
    .then((response)=> response.json())
    .then((responseJson) => {
        resolve(responseJson);
    })
    .catch((error) => {
        reject(error);
    });
});
}

db.json

{
  "users": [
    {
      "id": 1,
      "email": "[email protected]",
      "password": "12345"
    },
    {
      "id": 2,
      "email": "[email protected]",
      "password": "123456"
    },
    {
      "id": 3
    }
  ]
}

这就是登录功能

login(e){
      e.preventDefault();
      PostData(this.state).then((result) => {
        let responseJSON = result;
        console.log(responseJSON);
      });
    }

更改功能

  onChange = async (e) =>{
      this.setState({[e.target.name]: e.target.value} );
      console.log(this.state);
    }
javascript json reactjs authentication json-server
2个回答
1
投票

状态 201 已创建 - 它表示 POST 请求成功。 Status 200 是 GET 请求的成功代码


0
投票

使用get方法登录。你会得到带有单个对象的数组的响应。

export function PostData(userData){
// check here for same mail
let url = 'http://localhost:3001/[email protected]';

return new Promise((resolve, reject) => {
    fetch(url,{
        method: 'GET',
        body: JSON.stringify(userData)
    })
    .then((response)=> response.json(){
      if(response.data.lenth > 0){
        // you have object 
        // now check password
        if(response.data[0].password == enteredPassword){
          // login successfully
          // login opration here
        }else{
          // wrong password
        }
      } else{
        // wrong mail adress
      }
      
    })
    .then((responseJson) => {
        resolve(responseJson);
    })
    .catch((error) => {
        reject(error);
    });
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.