我用烧瓶和PHP制作了POC来实践这个概念。
@app.route('/api/connexion', methods=['POST'])
def conn():
login = request.form["login"]
password = request.form["password"]
response = make_response(jsonify({
'login':login,
'password': password
}))
response.set_cookie('token', 't1',httponly=True)
return response
使用php代码,我发送请求并获得响应,但是如何保存cookie以便在其他请求中通过其他API调用重用它?
myForm = document.getElementById("myForm")
myForm.addEventListener('submit', (e) => {
console.log("in event");
e.preventDefault();
let form = new FormData(myForm);
fetch("http://127.0.0.1:8000/api/connexion",{
method:'POST',
body:form
}).then((response) => {
return response.json();
}).then((text)=> {
console.log(text);
})
})
所以问题是:我是否需要获取cookie并手动保存它,否则cookie将在每个请求中自动发送,我想了解如何。非常感谢。
良好实践浏览器保存cookie后,它将在请求的 most
如何使用获取请求自动发送域cookie
{"credentials":"same-origin"}
。myForm = document.getElementById("myForm")
myForm.addEventListener('submit', (e)=>{
console.log("in event");
e.preventDefault();
let form = new FormData(myForm);
let fetchInitObject = {
method: 'POST',
body: form,
/*
The following line will tell the browser
to send all the cookies of the site in the URL, as long as
the url and the site that runs the Javascript code are from the same origin
In your example - the side that runs the javascript code, should be 127.0.0.1 in port 8000, without http
*/
credentials: 'same-origin'
};
fetch("http://127.0.0.1:8000/api/connexion", fetchInitObject).then((response)=>{
return response.json();
}
).then((text)=>{
console.log(text);
}
)
}
)