首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >[ Python ][Javascript]无法知道如何从NEXTjs网页GUI向Python后端发送API调用

[ Python ][Javascript]无法知道如何从NEXTjs网页GUI向Python后端发送API调用
EN

Stack Overflow用户
提问于 2020-02-21 11:04:30
回答 1查看 518关注 0票数 1

我试图使用一个简单的表单字段从NEXTjs前端向位于同一服务器上的后端发送POST请求,这是一个使用猎鹰库的python脚本。python脚本本身由Gunicorn运行,并侦听8080端口。

这两种代码运行良好,没有错误,但是当我尝试提交表单时,我得到的只是一个415错误,它似乎表明,我试图发送给API的不是一个受支持的媒体类型,而是正如这个回答中所指出的

Falcon对内容类型: application/json的请求有开箱即用的支持

由于网页和服务器都托管在相同的VPS上,我也尝试在获取调用中使用127.0.0.1地址,但也没有成功(后端API甚至没有响应)

下面是后端代码:

代码语言:javascript
运行
复制
#!/usr/bin/env python
# coding=utf-8


import time
import falcon
import json


class Resource(object):

    def on_post(self, req, resp, **kwargs):
        request_body = req.media

        print('POST Request: {}'.format(req))
        print('Request body: {}'.format(request_body))

        start = time.time()

        resp.body = json.dumps({
            'count_identical_pairs': count_identical_pairs(request_body),
            'computation_time': int((time.time() - start) * 1000)
        })


def count_identical_pairs(integers_array):
    total = 0
    count = dict()

    # Type checking
    if not isinstance(integers_array, list):
        return -1

    # Check if N is within the range [0..100,000]
    if len(integers_array) > 100000:
        return -2

    for integer in integers_array:

        # Check if each element of the array is within the range [−1,000,000,000..1,000,000,000]
        if integer not in range(-1000000000, 1000000000):
            return -3

        if str(integer) not in count:
            count[str(integer)] = 1
        else:
            count[str(integer)] += 1

    for key, value in count.items():
        total += value * (value - 1) / 2

    return total


api = application = falcon.API()

api.add_route('/count_identical_pairs', Resource())

这是前面的一个:

代码语言:javascript
运行
复制
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Index extends React.Component {
    constructor() {
        super();
        this.state = {
            input_array: [],
        };
        this.onSubmit = this.onSubmit.bind(this);
        this.myHeaders = new Headers();
    }

    onChange = evt => {
        // This triggers everytime the input is changed
        this.setState({
            [evt.target.name]: evt.target.value,
        });
    };

    onSubmit = evt => {
        evt.preventDefault();
        console.log('this.state.input_array = ' + this.state.input_array);
        console.log('JSON.stringify(this.state.input_array) = ' + JSON.stringify(this.state.input_array));
        // Making a post request with the fetch API
        // Test payload [1, 7, 7, 5, 7, 5, 6, 1]
        fetch('http://vps638342.ovh.net:8080/count_identical_pairs', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=utf-8'
            },
            mode: 'no-cors',    // Security hazard?
            body: JSON.stringify(this.state.input_array),
            redirect: 'follow'
        })
        .then(response => response.text())
        .then(data => console.log('Data: ' + data))
        .catch(error => console.log('Error: ' + error))
    };

    render() {
        return (
            <form onSubmit={this.onSubmit} >
                <input
                    name="input_array"
                    type="text"
                    id="name"
                    value={this.state.input_array}
                    onChange={this.onChange}>
                </input>
                <input type="submit" />
            </form>
        );
    };
}

ReactDOM.render(<Index />, document.getElementById("root"));

编辑1:我已经用Postman测试了python,我可以看到它已经运行得很好了,如图中所示:

编辑2:,感谢@Maku,这里是后端的更新代码,允许所有源、方法和头。我对服务器开发还不熟悉,但我猜这不是一种非常安全的编码方式,但至少它能工作(如果我找到了一种更推荐的方法,我会添加第三个编辑)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-21 11:30:04

在您的falcon服务器中启用CORS,并删除javascript中的“no-cors”标志,这在前几天对我起了作用。

https://github.com/lwcolton/falcon-cors应该为你工作。要测试它,您可以只允许使用类似的东西(我正在使用另一个python框架,所以我还没有测试过这个精确的falcon扩展)

代码语言:javascript
运行
复制
cors = CORS(allow_all_origins=True, allow_all_headers=True)

api = falcon.API(middleware=[cors.middleware])

编辑:添加了allow_all_headers=True,如注释中所讨论的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60337338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档