Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
'Axios' PUT request to server (URL failed)

I am fairly new to Node.js/Express.js/Axios/MongoDb/Mongoose, and it's my first time to ask in stackoverflow, so please correct me if I make any mistake in presenting the question.

I'm creating a website for novel, and I hope once the reader finish reading a chapter, his readedChapterIds(a property of user mongoose model) records the chapter ID that he just read.

First, I created the get&put route /:user_id in the folder route/user.js and controller/user.js, so users can edit their profiles in the website. I tested it and check it in mongoDB atlas to make sure that put route worked. Second, I tested the axios.get in my showChapter.js to make sure that axios CDN did worked. Third, I revised it as a put request. Here comes the problem.

    const currentUser = document.querySelector('#currentUser');
    const currentUserInString = currentUser.innerText;
    const chapterID = document.querySelector('#chapterID');
    const chapterIDInString = chapterID.innerText;

    const  readedChapterIds = { readedChapterIds: `${chapterIDInString}`}
    axios.put(`http://localhost:3000/${currentUserInString}`, readedChapterIds )
      .then(function (response) {console.log(response);})
      .catch(function (error) {console.log(error);}); 

and I got

PUT http://localhost:3000/ 404 (Not Found) Error: Request failed with status code 404 at e.exports (axios.min.js:1:8675) at e.exports (axios.min.js:1:13500) at XMLHttpRequest.E (axios.min.js:1:7067)

I tried /${currentUserInString} ${currentUserInString} 'http://localhost:3000/621832c2a7b93b0a95a1fb86' (the chapter ID I print using console.log).None of them work. I read the axios docuemntation and all related question in stackoverflow, but find no solution.

My first question: how to fix my url problem? My second question: should I use patch request instead of put request? I guess I should push the chapterID into the readedChapterIds array, so that he does not lose any reading record he had before. or Maybe keep the axios.put but add user.readedChapterIds.push(...readedChapterIds) in the controllers/user.js ???

Thanks in advance. I appreciate any answer and keep trying.

Edit:

Here is my server side code:

router.put('/:user_id', catchAsync(users.updateUser));

module.exports.updateUser = async (req, res) => {
const { user_id } = req.params;
const user = await User.findByIdAndUpdate(user_id, { ...req.body});
await user.save();
req.flash('succes', 'Successfully updated your User Profile!')
res.redirect(`/`)
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

server side problem has been solved by the following code :

module.exports.patchUser = async (req, res) => {
    // res.send('updating something')
    const { user_id } = req.params;
    const newRead = req.body.readedChapterIds;
    const user = await User.findById(user_id);
    user.readedChapterIds.push(newRead);
    console.log(user)
    await user.save();
    req.flash('succes', 'New Chapter Unlocks!')
    // res.redirect(`/`)
}

req.body wasn't readable due to the defauls headers, so I define the content type of the headers. In doing so, req.body is readable.

headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },

Here is the whole picture of my browser side code:

let data = new URLSearchParams();
data.append('readedChapterIds', `${chapterIDInString}`)
axios({
    method: 'patch',
    url: `/${currentUserInString}`,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: data
})
.then((response) => console.log(response))
.catch((error) => console.log(error))

Thanks everyone.

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is solved using Content-Type

let data = new URLSearchParams();
  // check it more at https://www.itread01.com/content/1577199910.html
  data.append('readedChapterIds', `${chapterIDInString}`)
  axios({
        method: 'patch',
        url: `/${currentUserInString}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    })
  .then((response) => console.log(response))
  .catch((error) => console.log(error))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda