1

Проблема заключается в том, что при каждом отправке запроса, я получаю новую сессию. Проблема кроется в credentials. Ставил и same-origin все равно ничего не дает. Я отправляю запрос на /signin и на /account. Мне нужно что все запросы осуществлялись на одной сессии.

Вот сервер:

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);

Запросы:

  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);
  },

Роутеры:

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);
});

Если использовать credentials: 'include' то с header, он не работает, а на сервер приходит undefined, но с одной сессией работает. Как реализовать работу запросов, чтоб на /signin он отправлял данные на одну сессию, а при вызове /account запрос работал с этой же сессией?

1 ответ 1

0

в конфиг куки

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

попробуйте добавить

 path: "/"

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.