Search code examples
jquerynode.jsajaxexpresshttp-status-code-404

GET request gives 404 error express js even though I have a well defined route in my express server


I am using Jquery's ajax request to get a JSON object from the server however when the request is invoked it gives a 404 error that looks like this:

Failed to load resource: the server responded with a status of 404 (Not Found) profile_data?uid=HW3gAHeiuJbQLMFQMbHA6nNlFUT2&_=1619880251360:1

As far as I am concerned all is done according to standard which is CRUD = Create:POST, Read:GET,Update:PUT and delete: DELETE. Please let me know of anything in my code is it wrong ? Here is the get request:

$(document).ready(()=>{
            $.ajax({
              url: '/profile_data',
              type: 'GET',
              cache: false,
              data: { "uid": uid},
              success: function(data){
                //Instantiate Variables of User Data
                

              }
              , error: function(jqXHR, textStatus, err){
                alert('text status '+textStatus+', err '+err)
              }
            });

          });

        } else {
          Window.locate.assign("/login");
        }
  });

This is the server side code:

app.get("/profile_data",   function (req, res){
    const current_user = req.body;
    const uid = current_user.uid;
    console.log(uid)
    db.ref("user_file_ref").on("value", snapshot=>{
        snapshot.forEach( dataSnapshot=>{
            if(uid === dataSnapshot.val().user_id){
                getFileFromNet(dataSnapshot.val().ipfs_ref).then( result =>{
                    const hash = JSON.parse(result);
                    let decrypted_string = decrypt(hash);
                    let return_data = JSON.parse(decrypted_string);
                    //console.log("Here!!")
                    res.send(return_data);
                }).catch(err =>{
                    console.log(err);
                });


            }
        })
    })
});

Solution

  • You should pass the parameter with URL.

    Like this:

     $.ajax({
              url: '/profile_data/' + uid,
              type: 'GET',
              cache: false,
              // data: { "uid": uid}
    

    and on the server-side.

    app.get("/profile_data/:uid",   function (req, res){
     const current_user = req.params.uid;
    }