axios.post到Django ConnectionResetError:[Errno 54]对等重置连接

时间:2020-04-05 18:02:53

标签: javascript django reactjs post axios

我为一个看似非常简单的任务而生气:使用React应用程序向django服务器执行发布请求。

发布请求(在React中):

static searchProducts(query) {
    console.log(queryString.stringify({'search_key':query}))

    const requestBody = {
        search_key: query
      }

    const config = {
        crossDomain: true,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Access-Control-Allow-Origin': '*'
        }
      }

    return axios.post(API_ROUTE+'/search/', 
        queryString.stringify(requestBody),
        config)
    .then(function (response) {
        console.log(response)
    })
    .catch(function (error) {
        console.log(error);
    });
}
Django后端中的

函数:

@csrf_exempt
def search(request):
if request.POST['search_key']:
    req=request.POST
else:
    req=json.loads(request.body)
if req['search_key']:
    if (req['search_key'][-1]) == " ":
        key=req['search_key'][:-1]
    else:
        key=req['search_key']
vector = SearchVector('name','brand','family','sub_family',config='italian')
query = SearchQuery(key,config='italian')
keys_array = key.split(" ")
print(key)
# rs = Product.objects.annotate(search=vector).filter(search=key)
# rs = Product.objects.annotate(search=vector).filter(search__icontains__in=keys_array)

q = Q()
for word in keys_array:
    q |= Q(search__icontains = word)
q |= Q(search=key)
rs= Product.objects.annotate(search=vector).filter(q)

rs=rs.annotate(rank=SearchRank(vector, query)).order_by('-rank').values()
print(rs)
return JsonResponse({'response':list(rs)})

请注意,后端确实可以正确打印rs,但随后引发以下错误:

ConnectionResetError: [Errno 54] Connection reset by peer

在FE上,错误是:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/search/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在做什么错?我为此而疯狂。

0 个答案:

没有答案