2017-05-25 60 views
1

我在聚合物2.0上使用iron-ajax时出现问题。我的代码基于Polymer 1.0,我试图去适应它。我通过POST发送我的形式是这样的:Iron-ajax 401未授权或CORS问题

模板:

 <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> 

代码:

_setReqBody() { 
     this.$.registerLoginAjax.body = this.formData; 
    } 

    postLogin() { 
     this.$.registerLoginAjax.url = 'http://localhost:3001/sessions/create'; 
     this._setReqBody(); 
     this.$.registerLoginAjax.generateRequest(); 
    } 

铁阿贾克斯设置:

<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> 

当我做我收到以下错误:

POST http://localhost:3001/sessions/create 400 (Bad Request)

当我使用的铁阿贾克斯这一行:

with-credentials="true" 

,因为它似乎是一个CORS问题的错误:

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.

我在做什么错?

+0

你对服务器端是什么?聚合物1是否正确工作?*? – Dmitry

回答

2

更改服务器端代码为http://localhost:3001/sessions/create后端从http://127.0.0.1:8081/发送响应头Access-Control-Allow-Origin: http://127.0.0.1:8081/在回应的请求,而不是回送响应头Access-Control-Allow-Origin: *,因为它是现在这样。

Credentialed requests and wildcards section of the MDN page on CORS解释了原因:

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.