![](/img/trans.png)
[英]Cookie not set in request header when request is sent from React
[英]Cookie not sent when with request
我對使用 API 進行 web 開發非常陌生。 所以我有一個 function 使用下面的代碼向服務器發送請求。 它與我存儲在 cookie 中的令牌一起發送。
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Content-Type", "text/plain");
var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
credentials: 'include',
};
fetch("http://127.0.0.1:8000/logs/log/", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
但是,當我嘗試發送它時,我不斷收到此錯誤。
https://i.stack.imgur.com/StU0q.png
經過一番挖掘,我注意到我的 cookie 沒有隨請求一起發送(如下圖所示)。 這對我來說很奇怪,因為我在 requestOptions 中將“憑據”設置為“包含”。
https://i.stack.imgur.com/Hp1mi.png
但是,當我注釋掉 append "Content-Type" 到 header 的行時,header 變為空。 cookie 再次包含在 header 中,以及最初未包含的其他標頭。
var myHeaders = new Headers();
// myHeaders.append("Content-Type", "application/json");
// myHeaders.append("Content-Type", "text/plain");
var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
credentials: 'include',
};
fetch("http://127.0.0.1:8000/logs/log/", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
https://i.stack.imgur.com/JJNbB.png
但是如果我沒有將“Content-Type”設置為“application/json”,我會收到“415 Unsupported Media Type”錯誤。
有誰知道這是為什么? 以及如何解決?
先感謝您。
我沒有足夠的聲譽來發布圖片,所以我將它們附加為 url
對於初學者,我建議為您的服務器設置 cors 策略,因為當您設置 Content-Type 時,您會收到此錯誤當您未設置 Content-Type 時,您將其放入有效負載 application/json 類型,但實際上您的 Content-Type:plain/文本。 所以,也許你這個請求的服務器只能處理 json 數據,而不是文本,所以你得到錯誤。 但這些只是我的假設
我忘了更新這個,但我找到了解決方案。 Cookies 不應該在預檢中發送。 在您的后端,您必須授予預檢權限(特別是 HTTP OPTIONS)。 在我的例子中,我使用 Django 和 django-rest-framework 所以我的示例解決方案看起來像。
class PreflightsOnly(permissions.BasePermission):
def has_permission(self, request, view):
return request.method == "OPTIONS"
class LogAPI(generics.GenericAPIView):
queryset = Log.objects.all()
permission_classes = [PreflightsOnly|permissions.IsAuthenticated]
serializer_class = LogSerializer
我仍然不知道為什么會發生這種情況。 但是,我有一個解決方法可以讓它工作。
我所做的是我決定根本不在 header 中設置“內容類型”。 所以我不得不堅持使用默認的“Content-Type: text/plain;charset=UTF-8”。 因此,為了完成這項工作,我制作了一個接受此“Content-Type”的自定義解析器。
from rest_framework.parsers import BaseParser
import ast
class PlainTextParser(BaseParser):
"""
Plain text parser.
"""
media_type = 'text/plain;charset=UTF-8'
def parse(self, stream, media_type=None, parser_context=None):
"""
Simply return a string representing the body of the request.
"""
byte_str = stream.read()
dict_str = byte_str.decode("UTF-8")
data = ast.literal_eval(dict_str)
return data
然后在我的 Django 應用程序的“settings.py”中,我像這樣設置 REST_FRAMEWORK DEFAULT_PARSER_CLASSES:
REST_FRAMEWORK = {
...,
'DEFAULT_PARSER_CLASSES': [
'rest_framework_customs.parsers.PlainTextParser',
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.