I'm having issues using iron-ajax on Polymer 2.0. My code's based on a Polymer 1.0 one and I'm trying to adapt it. I send my form through a POST like this:
Template:
<div class="wrapper-btns">
<paper-button raised class="primary" on-tap="postLogin">Log In</paper-button>
<paper-button class="link" on-tap="postRegister">Sign Up</paper-button>
</div>
Code:
_setReqBody() {
this.$.registerLoginAjax.body = this.formData;
}
postLogin() {
this.$.registerLoginAjax.url = 'http://localhost:3001/sessions/create';
this._setReqBody();
this.$.registerLoginAjax.generateRequest();
}
Iron-Ajax setup:
<iron-localstorage name="user-storage" value="{{storedUser}}"></iron-localstorage>
<app-data key="userData" data="{{storedUser}}"></app-data>
<iron-ajax
id="registerLoginAjax"
method="post"
content-type="application/json"
handle-as="text"
on-response="handleUserResponse"
on-error="handleUserError"></iron-ajax>
And when I do I get the following error:
POST http://localhost:3001/sessions/create 400 (Bad Request)
And when I use this line on the Iron-Ajax :
with-credentials="true"
The error as it seems is a CORS problem:
XMLHttpRequest cannot load http://localhost:3001/sessions/create. 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'. Origin 'http://127.0.0.1:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
What am I doing wrong?
Change the server-side code for the http://localhost:3001/sessions/create
backend to send the response header Access-Control-Allow-Origin: http://127.0.0.1:8081/
in responses for requests from http://127.0.0.1:8081/
, rather than sending back the response header Access-Control-Allow-Origin: *
as it’s doing now.
The Credentialed requests and wildcards section of the MDN page on CORS explains why:
When responding to a credentialed request, the server must specify an origin in the value of the
Access-Control-Allow-Origin
header, instead of specifying the "*
" wildcard.