最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handling sessions in React with Express.js backend API - Stack Overflow

programmeradmin1浏览0评论

I have a React app with backend API written in Express (all /api calls are proxied there).

Upon successful user authentication, I will be generating a session ID and storing it somewhere on the client side so that I can later authorise requests to the API.

What is the best practice of implementing this architecture on the Express side? Shall I just send the session ID along with the body of each API request and then precede all backend calls with an authorisation mechanism? Or is there some better/easier way of doing this?

I have a React app with backend API written in Express (all /api calls are proxied there).

Upon successful user authentication, I will be generating a session ID and storing it somewhere on the client side so that I can later authorise requests to the API.

What is the best practice of implementing this architecture on the Express side? Shall I just send the session ID along with the body of each API request and then precede all backend calls with an authorisation mechanism? Or is there some better/easier way of doing this?

Share Improve this question asked Dec 23, 2017 at 23:47 Marcin WasilewskiMarcin Wasilewski 7351 gold badge10 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

My intuition would be to take two steps.

  1. On the client, set up your HTTP client to pass the sessionID as a header. You can set custom headers using an HTTP client like axios or, in ES6, fetch, and apply those headers to every request send to your Express API.

  2. Set up a middleware function on your app that will run on every request received by the server. Express has an easy way to do this using app.all("*", yourAuthFunction). You can also take a look at app.use for applying a middleware to more specific routes. This will ensure that your sessionID gets verified on the server before any data is sent in response to the client. Of course, you'll have to write the auth function to work how you'd like.

Good luck!

When the user successfully authenticated (it should auth' anytime the page loads), a response should be sent to it (contains the session token). Every other request should be authenticated with the session token that received on the authentication response. You can store this token value into hidden input <input name="session" type="hidden" />

发布评论

评论列表(0)

  1. 暂无评论