python flask正确响应node.js中的fetch函数,但chrome控制台或网站javascript发出错误请求

6ie5vjzr  于 2023-02-15  发布在  Node.js
关注(0)|答案(1)|浏览(137)

为什么这段javascript代码可以在node.js中使用,而不能在chrome中使用?
顺便说一句,curl -X POST -H "Content-Type: application/json" -d '{"prompt":"testprompt"}' 192.168.122.234:3000/test也可以工作。
镀 chrome 错误与交叉原点无关:

VM10:4  POST http://192.168.122.234:3000/test net::ERR_ABORTED 400 (BAD REQUEST)

这里是flasktest.py:

from flask import Flask, jsonify, request, render_template
app = Flask(__name__)

@app.route('/test', methods=('GET', 'POST',))
def testfn():
    # GET request
    if request.method == 'GET':
        message = {'greeting':'Hello from Flask!'}
        return jsonify(message)  # serialize and use JSON headers
    # POST request
    if request.method == 'POST':
            print(request.get_json())  # parse as JSON
            

return 'Sucesss', 200

这是一段javascript代码:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin,>
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
    return response; // response.json() ??? parses JSON response into native JavaScript objects
}

postData('http://192.168.122.234:3000/test', {prompt: "hello" })
  .then((data) => {
    console.log(data); // JSON data parsed by `data.json()` call
  });
w8f9ii69

w8f9ii691#

虽然它没有给予cors错误的chrome浏览器问题被发现与cors有关。

pip3 install flask_cors

将其添加到服务器代码解决了以下问题:

from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/test', methods=('GET', 'POST',))
def testfn():
    # GET request
    if request.method == 'GET':
        message = {'greeting':'Hello from Flask!'}
        return jsonify(message)  # serialize and use JSON headers
    # POST request
    if request.method == 'POST':
        print(request.get_json())  # parse as JSON
        return 'Sucesss', 200

我们还需要更改模式:“no-cors”到“cors”,但是没有浏览器错误是误导......所以我没有删除这个问题,而是决定回答它。

相关问题