T.J
T.J

Reputation: 31

JavaScript - Cannot GET /api/list

I am working on a website where a user should be able to post items to a list. Right now, when I try posting something it comes up with an error saying

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).

When clicking on it in the console it opens a new tap where it just says

Cannot GET /api/list

Also in the command prompt, it says

Unhandled rejection Error: Can't set headers after they are sent.

Does anybody know why this might be and what I can do to fix it? Here are some snippets of my code:

Index.HTML:

fetch('/api/list', options)
    .then(response => response.json())
    .then(response => {
          if (response.status == 'OK') {
          console.log('song is added')
          getList(items)

          } else {
          alert(response.message)
        }
    })
 }

Server.js:

app.post('/api/list', userIsAuthenticated, (req, res) => {
  let {
    titleArtist
    } = req.body

   let user_id = req.session.user.id

   // seaching for user id in database
   let query = {
     where: {
     userId: user_id
    }
  }

It might also be somewhere else in the code it goes wrong. Let me know if I should post more snippets of code.

Upvotes: 3

Views: 609

Answers (1)

Code Guru
Code Guru

Reputation: 15598

This is because you are making a GET request to POST API.

This is how you can make POST request

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

Upvotes: 6

Related Questions