瓶子不认Axios.jsjsonpost

Bottle does not recognize Axios.js json post

我正在尝试使用 Axios 向编码在 Python bottle 中的后端发出 post 请求。

问题是当请求被触发时,我得到一个 500 internal

首先,这里是axios请求代码:

const data = {date: formatDate(date), titles}
post(`${API_URL}/save_day_titles`, data)
  .then(res => {
    console.log('response success', {...res});
  })
  .catch(res => {
    console.log('response', {...res});
  });

瓶子代码:

@planApi.route('/api/v3.6/save_day_titles', method=['POST', 'OPTIONS'])
def plan_save():
    date = request.json['date']
    titles = request.json['titles']
    plan = {
        'date': datetime.datetime.strptime(date, '%Y-%m-%d'),
        'titles': titles 
    }
    id = titlesMongo.insert_one(plan).inserted_id
    return {"id": str(id), "plan_date": date, "planification": titles}

Web 控制台中记录的错误简单明了:

OPTIONS xxx/api/v3.6/save_day_titles 500 (Internal Server Error)

XMLHttpRequest cannot load xxx/api/v3.6/save_day_titles. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.

它看起来像一个 CORS,但我正在发出很多其他请求(获取请求)并且没有 CORS 错误......无论如何,当我尝试在服务器中记录正文时:print request.body.parse() 日志是:

127.0.0.1 - - [17/Aug/2017 18:18:45] “POST /api/v3.6/save_day_titles HTTP/1.0” 500 765
b’'

奇怪的是,使用 CURL 请求成功:

curl -H "Content-Type: application/json" -X POST -d '{ "date": "2017-08-15", "titles": [{"title": "title test", "url":"xxx/xxx", "category": "category test"}] }' "xxx/api/v3.6/save_day_titles".

Axios 配置似乎没问题:

date: "{"date":"2017-08-01","titles":[{"title":"title test","url":"xxx/xxx","category":"category test"}]}"
headers:
  Accept: "application/json, text/plain, */*"
  Content-Type: "application/json;charset=utf-8"

所以,我只是被困在这里,无法找出问题所在,有什么想法吗?提示?

提前致谢。

您的浏览器正在执行 CORS preflight OPTIONS request,但是当您的服务器收到该请求时发生了一些内部故障,因此服务器 returns 对该请求作出了 500 错误响应。

当服务器发生内部故障并发送 500 错误响应时,服务器不会添加 Access-Control-Allow-Origin 响应 header,因此您最终会看到该 CORS 错误消息。

所以真正的问题不是 CORS 错误,而是服务器中的一些内部问题——因此,要找到解决方案,您需要查看服务器端的服务器日志并查看当发生 500 错误时,服务器正在记录有关原因的消息。

The weird thing is, with CURL the request is succesful:

curl -H "Content-Type: application/json" -X POST \-d '{ "date": "2017-08-15", "titles": [{"title": "title test", "url":"xxx/xxx", "category": "category test"}] }' "xxx/api/v3.6/save_day_titles".

这是在测试 POST 请求。您的浏览器永远不会执行 POST;相反,它首先执行 CORS preflight OPTIONS request,但是当它收到对 OPTIONS 请求的 500 错误响应时,这是预检失败,因此浏览器永远不会继续执行 POST.

因此,要使用 curl 模拟浏览器行为,您首先需要发送一个 OPTIONS 请求:

curl -X OPTIONS -i -H 'Origin: http://localhost:3000' \
    -H 'Access-Control-Request-Method: POST' \
    -H 'Access-Control-Request-Headers: Content-Type' \
    xxx/api/v3.6/save_day_titles

这应该会让服务器返回您在浏览器中看到的相同的 500 错误响应。

请注意,浏览器之所以这样做 CORS preflight OPTIONS request 是因为您的前端 JavaScript 代码正在添加 Content-Type: application/json 请求 header,这是触发浏览器进行预检。