V
V
Vadim V2019-03-15 17:27:42
Node.js
Vadim V, 2019-03-15 17:27:42

How to make automatic POST request to front api?

On expressJS, you need to do authorization if you have a token. If there is a token in the cookie, you need to make a POST request to api ... The question is, how can this be done? That is, the presence of a token in cookies is checked when the page is reloaded, and the user is searched for by the token and authorized.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-03-15
@reyzele

for express there is node-fetch
we check the cookie through cookie_parser and if it is correct, then we just call and make a request

if (req.cookies.mySuperCookie === 'valid') {
  const apiResults = await fetch('./api/mySuperApi', {method: 'post'} )
  .....
  return ..
}

I just tried it, everything works, but an addition - you need to specify the "absolute" address for the request, I found in the comments how to do it
https://github.com/zeit/next.js/issues/1213#issuec...
const baseUrl = req ? `${req.protocol}://${req.get('Host')}` : '';
  const response = await fetch(baseUrl + '/posts');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question