2017-05-25 92 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.