1

I tried to submit the HTML Form in the following ways.

  • Single demo HTML File. - It works (No errors and HTTP 200 response code)
  • Submitted the form using the Chrome POSTMAN plugin - It works (No errors and HTTP 200 response

But, when I am trying to submit the same form.

  • Using Angular2 - Form submitted Successfully (Has Error and HTTP 200 response code)

Here is the error

XMLHttpRequest cannot load https://docs.google.com/forms/d/e/1FAIpQLSfXzWPpI4X9ghY_6p5ghJRt6DC80FnrKqlw8lUg-OT-bKzBeg/formResponse. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I found some similar questions like 1 2 3 in SO and I now know that the error is not related to Angular2.

My question is has 2 parts.

  1. If this is something that has to be fixed at server side for clients to access smoothly, then how is it working when submitted directly from HTML file and POSTMAN plugin?
  2. When submitted using Angular2, though there is Access-Control-Allow-Origin error in console, the form is successfully submitted with HTTP response code 200, how should I understand this, why 200 response code, if there is an error?

Here is my angular2 code, May be it has an issue?

this._http
.post(this.postUrl, data)
.subscribe(data => {
    console.log('Congrats your feedback is recorded...'); 
    // this is not printed in console.log so far 
}, error => {
    console.log(error.json()); 
   // No 'Access-Control-Allow-Origin' header is present on the requested resource.
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
srk
  • 4,857
  • 12
  • 65
  • 109

2 Answers2

1

It's not a server-side issue per se. The server just chose not to allow cross-origin requests from your domain (or didn't even think about allowing them).

The issue is that, unless the server allows it, the browser refuses to send AJAX requests to a server on a different domain. That's mandated by the CORS specification that browsers implement.

A classical form doesn't use AJAX, so that works fine.

A Chrome plugin isn't subject to the same CORS restrictions as a traditional HTML page loaded from a server, so that works fine, too.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

As per browser policy CORS is not allowed in browser. However these restriction is not applicable for POSTMAN. Hence it should be fixed in backend not in front end.

Remember:

  • If your are requesting from localhost:4200 to localhost:4200/api CORS wont occur.
  • CORS error only occur when different server request.

    How to solve these issues?

    1. Consider If you are using express as your backend.
    2. You should add Middleware to access your routes.

app.use(function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*');
    //res.header('Access-Control-Allow-Headers','authorization');
    next();
});
thangavel .R
  • 466
  • 4
  • 13