Access to XMLHttpRequest has been blocked by CORS policy
There are two ways this can be handled:
- Temporary Front-End solution so you can test if your API integration is working:
Click on window -> type run and hit enter -> in the command window copy:
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
This will open a new "Chrome" window where you can work easily. This is a temporary solution. Every time you will have to work with this chrome window.
- Permanent solution:
In the backend code, the developer needs to add an annotation @Crossorigin right above the CRUD api call method.
Let me know if it works.
use this in Node
app.use(function (req, res, next) { //Enabling CORS res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization"); next(); });
And in angular the request is
auth(login): Promise<any> { return new Promise((resolve, reject) => { this._http.post('url:3000/api/auth/login', { ...login }) .subscribe((response: any) => { resolve(response); }); });}
Your error:
Access to XMLHttpRequest at
'my_url'
from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My error:
Access to XMLHttpRequest at
'localhost:3000/api/todo'
from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
(Even though a bit different error but i'll answer anyway)
Now two questions here:
- How did i resolve my issue?
Ans. Putting 'http://' before api i used, means 'http://localhost:3000/api/todo'.
- What might've caused your error?
Ans. Can't say for sure but i dont see your api url instead it says 'my_url' (comparing both errors). I thik you may've passed string instead of variable.
I'll be happy if this helps anyone. Because this cost me almost 2hr and now it's midnight(almost).