Search code examples
ubuntunext.jsvapor

Access to XMLHttpRequest has been blocked by CORS


I use Vapor for backend and Next.js for front end on Ubuntu and want to access database this way:

    let cq = {
      text: "My question",
    }; 
    axios({
      method: "post",
      url: `http://localhost:8080/createQuestion`,
      data: cq,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "http://localhost:3000",
      },
    }).catch((err) => console.error(err));

I got this response: Access to XMLHttpRequest at 'http://localhost:8080/createQuestion' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can it be that

"Access-Control-Allow-Origin": "http://localhost:3000"

is presen in the code and I got the previous error message. I even tried "Access-Control-Allow-Origin": "*", but it did not help.


Solution

  • You've added the CORS header to your JavaScript - it should be added to the Vapor app and returned in the response from Vapor. See the Vapor docs for information on adding the CORS middleware