2017-06-18 75 views
0

我有一個正在與節點後端交談的反應前端。我能夠提出請求等。不過,我注意到我無法設置我回來的cookie。我的後端將在登錄時作出響應,並附帶一條消息和一個cookie。我應該怎麼做?ReactJS如何將Cookie從提取請求設置爲後端

相關代碼:

import React from "react"; 
import Fetch from 'react-fetch'; 

export class Loginform extends React.Component{ 
    constructor(){ 
    super(); 
    this.state = {message : ""}; 
    this.state = {cookie : ""}; 
    } 

    Login(e){ 
    e.preventDefault(); 
    var Email_Address = this.refs.Email.value; 
    var Password  = this.refs.Password.value; 

    fetch("http://localhost:5000/api/form", { 
     method: "POST", 
     headers: { 
      "Content-Type":"application/json", 
      "Accept":"application/json" 
     },credentials: "include", 
     body: JSON.stringify({ 
      Email_Address: Email_Address, 
      Password: Password 
     }) 
     }).then(response=>response.json()) 
     .then(response => this.setState({message: response.Message, cookie :response['x-access-token']})); 
    } 

    render(){ 
     return(
    <div className="LoginContainer"> 
    <form name="Loginform" method="post" action="http://localhost:5000/api/tavern" onSubmit={this.Login.bind(this)}> 
    <div className="block"> 
    <label><i className="fa fa-envelope"></i></label> 
    <input ref="Email" type="email" placeholder="E-Mail" required title="Enter Valid E-Mail Address"/> 
    <i className="fa fa-check" aria-hidden="true"></i> 
    </div> 
    <div className="block"> 
    <label><i className="fa fa-lock"></i></label> 
    <input ref="Password" type="password" placeholder="Enter Your Password" pattern=".{9,}" required title="9 Characters Minimum"/> 
    <i className="fa fa-check" aria-hidden="true"></i> 

    </div> 
    <div className="returnmessage"> {this.state.message}</div> 
    <div className="buttons"> <button type="submit" value="Submit">Login</button></div> 
    </form> 
    </div> 
     ); 
    } 
} 

我不得不添加此作出以下適用的答案:
NPM安裝反應餅乾--save
進口餅乾從「反應餅乾」

這是我的代碼之後。

fetch("http://localhost:5000/api/tavern", { 
     method: "POST", 
     headers: { 
      "Content-Type":"application/json", 
      "Accept":"application/json" 
     },credentials: "include", 
     body: JSON.stringify({ 
      Email_Address: Email_Address, 
      Password: Password 
     }) 
     }).then(response=>response.json()) 
     .then(function (data){ 
      console.log(data); 
      cookie.save('x-access-token', data['x-access-token']); 
      this.setState({message: data.Message, cookie :data['x-access-token']}) 
     }.bind(this) 
    ) 

    } 

回答

2

你在做什麼不是設置cookie。你只是在稱爲cookie的狀態下創建一個變量。

安裝this包。

正確的語法是

Cookies.set('access_token', response.headers['x-access-token']) 

現在,它實際上是存儲在您的瀏覽器cookie。您可以繼續並使用

Cookies.get('access_token') 
+0

cookie未定義。我是否需要爲此安裝任何軟件包? – ApertureSecurity

+0

我用這個答案解決了這個問題。但是,我會在我的問題中添加一些細節。 – ApertureSecurity

+0

對不起,我忘了提包更新了答案。 –

相關問題