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)
)
}
cookie未定義。我是否需要爲此安裝任何軟件包? – ApertureSecurity
我用這個答案解決了這個問題。但是,我會在我的問題中添加一些細節。 – ApertureSecurity
對不起,我忘了提包更新了答案。 –