0

I am creating an angular application which involves working with API. I have created an API on my localhost and tried to request on it with AJAX. But it shows me the CORS error. I tried everything to solve this but nothing worked even from the stackoverflow. It shows me error like

Access to XMLHttpRequest at 'localhost/graphql' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I do this?

Yogesh Aggarwal
  • 1,071
  • 2
  • 12
  • 30

1 Answers1

1

You must use the same origin. The site is at http://localhost:4200 but you are trying to access http://localhost.

Add the port so that they both match, e.g. send your request to http://localhost:4200/graphql

Alternatively, add some CORS headers on your server.

Access-Control-Allow-Origin: http://localhost:4200

You can do this in Express with the cors middleware If you are on express server just add the following line:

const cors = require("cors")  // npm i cors
app.use(cors())

Read more about CORS on MDN

Codebling
  • 10,764
  • 2
  • 38
  • 66