-1

the API for login provides userId,name and sessionId (for Cookies) when parameters are given in JSON body. here is the example code via POSTMAN

    var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "sessionId=eyJhbGciOiJIUzI1NiJ9.MTY4OTI0Nzk3MDcwNzBsdGlheGYycThuaA.oD6XM_s3tAdv6eBxjierxoH_KK-Mc1qvyOR5CpDStMY");

var raw = JSON.stringify({
  "email": "[email protected]",
  "password": "newPassword"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://mcqapi.onrender.com/api/users/login", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

the sessionId myHeaders.append is being given in response by API every time but how will it work for the other web pages of the website e.g. I have this code on the other page of the website but it will only work if there are cookies in the header

fetch("https://mcqapi.onrender.com/api/topics", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => {
    const topics = data.map((topic, index) => `${index + 1}. ${topic.questionTopic}`);
    const titleElements = document.querySelectorAll('.title');
    titleElements.forEach((element, index) => {
      element.textContent = topics[index];
    });
  })
  .catch(error => console.log(error));

I have tried saving sessionId in localstorage and retrieve its value for other page but it didn't work

fetch("https://mcqapi.onrender.com/api/topics", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Cookie': 'sessionId=' + localStorage.getItem('sessionId')
  } 
})
.then(response => response.json())
.then(data => {
  const topics = data.map((topic, index) => `${index + 1}. ${topic.questionTopic}`);
  const titleElements = document.querySelectorAll('.title');
  titleElements.forEach((element, index) => {
    element.textContent = topics[index];
  });
})
.catch(error => console.log(error));

4
  • do you have an error messages? Commented Jul 12, 2023 at 15:12
  • yes @luke Access to fetch at 'mcqapi.onrender.com/api/users/login' from origin 'muhammadp3.sg-host.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include' I get this while applying this code: Commented Jul 12, 2023 at 16:07
  • CORS stands for Cross Origin Resource Sharing, and must be configured on the server to allow requests from a specific "origin" (in this case, sg-host.com). Edit your question with details about what you're building, where the api service and web app frontend are hosted, what frameworks they do, etc..., and I'll write a comprehensive answer based on that Commented Jul 12, 2023 at 17:48
  • 1
    I am changing the question to be more clear please have a look at it @luke Commented Jul 13, 2023 at 11:30

1 Answer 1

-1

Storing the session ID cookie in some kind of local storage is indeed the correct way to implement what you're trying to implement. Based on the comments, however, your trouble is with CORS, or Cross Origin Resource Sharing. Modern browsers require CORS to prevent cross site scripting, but local tools such as cURL or Postman will process the request regardless of if CORS is configured or not (since they aren't browsers).

At a low level, CORS works as follows:

  • Before sending the real HTTP request, the broswer sends a "preflight" request which is meant to verify that the web server accepts cross site requests from the origin (or client).
  • This preflight request includes a header called Origin which denotes where the request is coming from (either muhammadp3.sg-host.com or sg-host.com based on your comment).
  • If the server accepts any cross origin requests, it responds with the requested data along with a header called Access-Control-Allow-Origin, which is either the URL of the allowed origin or the "wildcard" * (important caveats exist when using *, which is part of your issue).
  • If all is copacetic in the previous steps, the browser proceeds to make the actual request with origin and Access-Control-Allow-Origin headers, along with others in certain scenarios, and receive a response (just like you've been doing in Postman)

Crucially, using the wildcard * is only allowed in special circumstances (code which is intended to be accessible from any site, for instance a font from Google Fonts). You cannot perform any kind of HTTP authentication, trade ssl certificates or set cookies using the wildcard *. To do these operations, you must configure the server with a whitelist of allowed sites, and to return the correct origin when it receives a request from an allowed origin.

Your question didn't mention what tools and frameworks you are using for the server, or the client application. The client application seems to be in base javascript, and the setup using the fetch API seems good (the Origin header is automagically included when using fetch(). Generally this kind of configuration would be done in nginx, apache or whatever reverse proxy or web server your backend is using. If you happen to be using express, the cors middleware is also a decent tool for development.

Update your question with details about the server configuration, and I'll try to find more specific documentation on how you can configure your server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.