Advertisement
Guest User

API

a guest
Feb 15th, 2022
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. I'll omit some stuff to make it extra simple with the purpose of illustrating the process. You can have something like this on the front end:
  2.  
  3. const noteObject = {
  4. content: newNote,
  5. date: new Date().toISOString(),
  6. important: Math.random() > 0.5,
  7. }
  8.  
  9.  
  10. You want to create a new note object with some content, date, and importance. You want to handle this data. In the link I provided— and for this particular example— they created a separate directory called "services" which is how you are going to handle the requests on the front end. To be able to use these services you need to import it:
  11.  
  12. import noteService from './services/notes'
  13.  
  14. This is the path of services. noteService is just an alias to be able to use it. You can call it whatever you want. You are ready to create your note:
  15.  
  16. noteService
  17. .create(noteObject)
  18. .then(returnedNote => {
  19. setNotes(notes.concat(returnedNote))
  20. setNewNote('')
  21. })
  22.  
  23. I am not going to explain each detail here since you can just do that tutorial and learn from there. But noteService will receive this statement and send it to the back end. This is the operation:
  24.  
  25. const create = newObject => {
  26. const request = axios.post(baseUrl, newObject)
  27. return request.then(response => response.data)
  28. }
  29.  
  30. This is basically what you are doing in postman. You are creating a baseURL (let's call it /api/notes) and that's what you will receive on the back end:
  31.  
  32. app.post('/api/notes', (request, response, next) => {
  33. const body = request.body
  34. //more stuff here
  35.  
  36. And that's it. This is what I explained to you. You have several endpoints in the back end (above) which is how you handle the requests you send in from the front end. I highly suggest you do that course. Doing simply the first 3 parts will give you a great understanding on how API calls work.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement