简体   繁体   English

Javascript 与 Python 通信

[英]Javascript Communicating with Python

I am attempting to send data from a Javascript program to a python program using python -m http.server as a means to run it locally.我正在尝试使用 python -m Z80791B3AE7002CB88C246876DFA 将数据从 Javascript 程序发送到 python 程序 -m Z80791B3AE7002CB88C246876DFA 在本地运行。 When I run it, the error message I get is: [HTTP/1.1 501 Unsupported method ('POST') Here is the useful portion of my javascript:当我运行它时,我得到的错误消息是:[HTTP/1.1 501 Unsupported method ('POST') 这是我的 javascript 的有用部分:

document.addEventListener("DOMContentLoaded",() => {

  document.querySelector("#search_button").addEventListener("click", (e) => {
    document.getElementById("company").innerHTML = document.getElementById("search").value;
  });

  document.querySelector("#week").addEventListener("click", (e) => {
    var time = 1;
    fetch("/yahooFinanceAPI.py", {
      method: 'POST',
      headers:{'Content': 'application/JSON'},
      body: JSON.stringify({
        'Company' : document.getElementById("search").value,
        'Time' : time
      })
    }).then(function(response)
    {
      console.log(document.getElementById("search").value);
    })
  });

Here is the useful python:这是有用的 python:

@bp.route('/SecurityBenefit.js', methods = ['POST'])
def get_post_javascript_data():
    if request.method == 'POST':
        data = request.get_json()
        ticker = data['Company']
        timespan = data['Time']
        print (ticker)
        print (timespan)
    return getPlot(ticker, timespan)

Does the python program need to run in the background for the program to register? python程序是否需要后台运行程序才能注册? Do I need to implement a do_POST function in my python?我需要在我的 python 中实现 do_POST function 吗?

I'm under the impression that I think you may have misunderstood how HttpRequests work.我的印象是我认为您可能误解了 HttpRequests 的工作原理。 You don't reference the file, you just reference the route, here is a fix:您不引用文件,只引用路线,这是一个修复:

JavaScript Code: JavaScript 代码:

    fetch("/javascriptPost", {
      method: 'POST',
      headers:{'Content': 'application/JSON'},
      body: JSON.stringify({
        'Company' : document.getElementById("search").value,
        'Time' : time
      })
    }).then(function(response)
    {
      console.log(document.getElementById("search").value);
    })

Python Code: Python 代码:

@bp.route('/javascriptPost', methods = ['POST'])
def get_post_javascript_data():
    if request.method == 'POST':
        data = request.get_json()
        ticker = data['Company']
        timespan = data['Time']
        print (ticker)
        print (timespan)
    return getPlot(ticker, timespan)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM