简体   繁体   中英

Can I use the JavaScript fetch to store form data in-memory?

I am setting up a demo signup form where users can create an account. The signup credentials provided should be stored in-memory or to a user file (user.json) and can be used to login and be redirected to the user profile page.

I have created a user.json file and put a sample user details in it. I can use fetch to console.log() the user details from the user.json file, but how do I add more users to the file using fetch?

The code I have tried:

let bodyData = {
  id: 2,
  name: "sarah",
  email: "sarah@gmail.com"
};

let postData = {
  method: "POST",
  body: JSON.stringify(bodyData)
};

// POST data to json file
fetch("./jsonfile/user.json", postData)
  .then(data => console.log(data))
  .catch(error => console.log(error));

// GET data form json file
fetch("./jsonfile/user.json")
  .then(res => res.json())
  .then(data => {
    data = JSON.stringify(data);
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });

I should be able to see in the output of console.log the new user added;

One route you could take is to abstract away the "storage implementation" from your code. You can do this by building an API which your code uses. Then build the API in a way that you can easily swap out implementations. This way, you can easily use an HTTP API, an in-memory DB , or even localStorage without mucking with your code.

Alternatively, you can use Service Workers to intercept network requests and do something with them, like for instance, load up data into localStorage and store them into localStorage.

JavaScript has some APIs for storing data in computer memory (for example localStorage ), but this is a very bad practice when storing credentials because only the user will have access to credentials. I advice you to set up a small database with server, for example Koa server & MongoDB database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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