The problem is that every time I send a request, I get a new session. The problem lies in the credentials . He put the same-origin and still does not give anything. I am sending a request to / signin and to / account. I need that all requests were carried out in one session.

Here is the server:

 app.set ('port', process.env.PORT || 8080);

 app.use (express.static (__ dirname + '/ public'));
 app.use (morgan ('dev'));
 app.use (bodyParser.json ());
 app.use (cors ({origin: '*'}));
 app.use (session ({
     store: new MongoStore ({
         url: `mongodb: // UserES6: foobar @ localhost: 27017 / $ {config.db.name}`,
     })
     secret: 'thisismysupersecret',
     resave: false,
     saveUninitialized: false,
     cookie: {
         httpOnly: false, // key
         maxAge: null
     }
 }));

 const server = app.listen (config.serverPort, () => {
     console.log (`server is up on $ {config.serverPort} port`);
 });
 app.use ('/', authRouter);

Queries:

 
 SignIn (data) {
        return fetch (`$ {apiPrefix} / signin`, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application / json'
            },
            body: JSON.stringify (data),
        })
             .then (response => response.json ())
             .then (data => console.log ('Response', data))
             .catch (console.error);
     }

 getUser () {
       return fetch (`$ {apiPrefix} / account`, {
           method: 'POST',
           credentials: 'same-origin',
       })
           .then (response => response.json ())
           .catch (console.error);
     },

Routers:

 router.post ("/ signin", (req, res, next) => {
     res.setHeader ('Access-Control-Allow-Credentials', 'true');
     user.findOne ({username: req.body.username, password: req.body.password}, ​​function (err, user) {
         if (err) {
             console.log (err);
             return res.status (500) .send ();
         }

         if (! user) {
             return res.status (404) .send ();
         }

         req.session.user = user;
         return res.status (200) .send ();
     })
 });

 router.post ('/ account', function (req, res) {
     res.setHeader ('Access-Control-Allow-Credentials', 'true');
     console.log (req.session.user);
    if (! req.session.user)
        return res.status (401) .send ();
    return res.send (req.session.user);
 });

If you use credentials: 'include' then with the header, it does not work, and the server receives undefined, but it works with one session. How to implement requests work, so that on / signin it sends data for one session, and when you invoke / account, the request worked with the same session?

    1 answer 1

    in the config cookie

      cookie: { httpOnly: false, // key maxAge: null } 

    try to add

      path: "/"