【问题标题】:Python is throwing error, "TypeError: 'NoneType' object is not subscriptable"Python 抛出错误,“TypeError:'NoneType' 对象不可下标”
【发布时间】:2020-12-29 05:44:22
【问题描述】:

我正在通过我的 html 表单提交信息,并希望 JS axios 处理表单提交以通知我的 API 有关传入的数据。但是,我不断收到一个类型错误,告诉我“nonetype 对象不可下标”。这是我的代码:

我将数据发送到的 Python 路由

@app.route("/api/cupcakes", methods=["POST"])
def create_cupcake():
    new_cupcake = Cupcake(flavor=request.json["flavor"], size=request.json["size"],
                          rating=request.json["rating"], image=request.json["image"])
    db.session.add(new_cupcake)
    db.session.commit()

    response_json = jsonify(cupcake=new_cupcake.serialize())
    return (response_json, 201)

HTML 表单

    <form action="/api/cupcakes" method="post">

        <label for="flavor">Flavor:</label>
        <input type="text" name="flavor"><br>

        <label for="size">Size:</label>
        <input type="text" name="size"><br>

        <label for="rating">Rating:</label>
        <input type="number" step="any" min="0" max="100"
            name="rating" placeholder="Enter a rating"><br>

        <label for="image">Image</label>
        <input type="url" name="image" placeholder="Enter an image url"><br>

        <input class="btn" type="submit" value="Submit Cupcake">
    </form>

JS

async function postCupcake() {
    let res = await axios({
        method: 'post',
        url: '/api/cupcakes',
        data: {
        flavor: flavor,
        size: size,
        rating: rating,
        image: image
        },
        headers: {
        'Content-Type': 'application/json'
        }
    })
    console.log(res)
}


$(".btn").submit(function(event) {
    postCupcake()
    event.preventDefault();
  });

这是我的错误照片

【问题讨论】:

    标签: javascript python axios


    【解决方案1】:

    我认为这个问题很可能是因为Content-Type。默认情况下,axios 在 HTTP POST 请求中使用 application/x-www-form-urlencoded Content-Type 标头。所以尝试将内容类型更改为'application/json'

    async function postCupcake() {
        let res = await axios.post('/api/cupcakes', {
            flavor: flavor,
            size: size,
            rating: rating,
            image: image
        },headers: {
            'Content-Type': 'application/json',
        })
        console.log(res)
    }
    

    【讨论】:

    • 感谢您的回复。然而,这似乎并没有解决问题。我仍然收到同样的错误
    • @rudehlabya 你能尝试在烧瓶函数中打印request.mimetype吗?
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多