Receive token without html form

Hi every body, am actually new into website dev. Right now am developing a website on glitch, i have finally created signup and login. now a user can login and receive a token. But my challenge now is how i can create an input for a login user to put back the token they receive. I wish to do that with post method, but not html form. On the server i have set up to retrieve user it , and i pass the token to the header: please help the link: Glitch

Hello!

I assume you mean you’re using something like OAuth or JWT, right? If so, your web application is responsible of maintaining the state, not your user.

You would authenticate your user, the server should return the token on a cookie and then that is sent with every request. You could also receive the token, store it on the localStorage (for instance) and then send it for every request:

// After the user clicks login

const credentials = {
  username: 'the_user',
  password: 'aVerySecurePassword',
};

const settings = {
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  body: JSON.stringify(credentials)
}
const response = await fetch('your_api/authenticate');

if (response.ok) {
  const token = await response.json();
  console.log('The token response:', token);
  localStorage.setItem('the_token', token);
}

Then, whenever you need access to an endpoint that requires a user to be authenticated (that is, a secured or private endpoint), you simply add the stored token:

const token = localStorage.getItem('the_token');

if (!token) throw new Error('Not authenticated'); // Or redirect to login

const theData = {
  hello: 'World',
};

const settings = {
  method: 'post',
  headers: {
    Authentication: `bearer ${token}`,
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(theData),
};

const response = await fetch('your_authenticated_ep/route', settings);

if (response.ok) {
  const result = await response.json();
  console.log('Result of authenticated post:', result);
}

That’s basically it. You would need to adapt it to your needs (integrate the code), but I hope it helps :slight_smile:.

1 Like

Thank you so much I really appreciate

1 Like

Hello skaparate, i wish to be testing every work am doing, to see each step i made a mistake so that i can make corrections. You made a good correction witch i created a post but i cant seems to test it. Am using postman to test, but it seems something is wrong. i thought i can post , get etc on postman, but reverse is the case here . For example am trying to test my login/register page and it is showing me bad request. can you help. the picture of my input below:


Those are the import i make and its showing error

I tested it and it’s working for me:

Here’s the Body tab:

i guess they must be a mix up some where then, let me quickly state the input. i pick:

  1. body
  2. post
  3. where there is none : Raw
    4finally json
    i might correct or i left something out/wrong pick???

In the headers tab, add: Content-Type: application/json:

1 Like

i think is not the input problem, cause its rather showing me the validation result.

{

    "errors": [

        {

            "msg": "input must be email",

            "param": "email",

            "location": "body"

        },

        {

            "msg": "please type a valid password",

            "param": "password",

            "location": "body"

        }

    ]

}

i will keep tying , think its posting, but it is encountering an error. actually, my input stop at body and the header , so if there is no other input then …
thanks once again

Could you show me the Headers and Body tabs as you’re sending them?

1 Like


for the header, i only type" Content-Type"
and application/json


and this is for the body : where i selected json,raw,input the api of the login, and post
May be it will be better if you make a simple table for me to follow its will be easier, cause i seriously need this to test my work…

The thing is that it is working :stuck_out_tongue:. If it didn’t you wouldn’t receive that response. You’re sending the wrong parameters to the endpoint. Try logging them, like this:

/login router
router.post(
  "/login",
  [
    (err, req, res, next) => {
      console.log('Body params:', req.body);
      next();
    },
    check("email", "input must be email").isEmail(),
    check("password", "please type a valid password").isLength({
      min: 6
    })
  ],

By the way, I meant the Body tab with the data you’re sending to the server, not the Response Body. In your last picture you’re showing the response only:

See? The tab to the right of Headers (7) in your last picture.

1 Like

sorry I could not reply you, cause my subscription got finished. So I could not.I should be on line tomorrow.

I will check and effect the change, and quickly give you a feed back. tomorrow

1 Like

greetings skaparate, i have added the code you sent to me and the result is still the same `//login router
router.post(
“/login”,
[
(err, req, res, next) => {
console.log(‘Body params:’, req.body);
next();
},
check(“email”, “input must be email”).isEmail(),
check(“password”, “please type a valid password”).isLength({
min: 6
})
],
async (req, res) => {
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}

try {
  const { email, password } = req.body;

  let user = await User.findOne({
    email
  });
  if (!user) {
    res.status(400).json({
      mssge: "account not found"
    });
  }else{      

let comparepassword = await bcrypt.compare(password, user.password);
if (!comparepassword) {
res.status(400).json({
password: “failed to compare, please try reloading”
});
};
const payload = {
user:{
id: user.id
},
};
const signToken = jwt.sign(payload, “mysecret”, {
expiresIn: 1160
}, function(err,token){
if(err)throw err;
return res.status(200).json({
token
})
});

}   
   }catch (error) {
  return error;
   }

});
`
This is the url to the login
https://pass-req-form.glitch.me/user/login
Now, when going to the postman i serve the following

  1. the url above to the url input
    2.choose post ,cause of course am posting the data .
  2. choose header and type “Content-Type and value= application/json”
    4 finally choose “raw” shift by the right and choose json instead of text because is a json body work. yet this is not working . And you said is working for you what do you suggest could be the problem.

That’s strange… Honestly, I don’t know why it’s not working for you. You’ll have to debug it on your side, because at least for me, it’s returning the authorization token (as shown on th previous pictures).

What does the console log on glitch?

1 Like

I was able to do it, I selected post, then i ignore raw and choose www urlencoded , then i read from their article that postman can select the header for you even if you leave it blank. then since i choose urlencoded i put in the keys and value as password and email.
https://learning.postman.com/docs/sending-requests/requests/ this is what help me

1 Like

Reading from: https://learning.postman.com/docs/sending-requests/requests/ made me understand much.
like when operating with form data, urlencoded is the default and the best for parsing. It now remind me when i coupled signup, it could not work until the midleware urlencoded. so i think it has to do with been good in setting up, postman. and I guess you used raw and all that and you still got it, a question should be that is my version different?? some times there one of these issues . Above all thanks for the attention. Am planning on using passport instead of cookies cause its do all the assignment.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.