Home > Blockchain >  'Axios' PUT request to server (URL failed)
'Axios' PUT request to server (URL failed)

Time:03-01

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(`/`)
}

CodePudding user response:

server side problem is 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(`/`)

}

Thanks everyone.

CodePudding user response:

Well... I just successfully send the patch request using axios.patch. Now new problem appears. req.body is empty, so I cannot update any information. Still fixing.

Edit: 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))
  • Related