【问题标题】:Send post request with Javascript使用 Javascript 发送 post 请求
【发布时间】:2021-12-15 09:08:37
【问题描述】:

我在 python 中有这个工作 API,如何在 javascript 中重新构建相同的东西?如果不可能,我如何从字体端发送这个 POST 请求?

import requests

gfg_compiler_api_endpoint = "https://ide.geeksforgeeks.org/main.php"
languages = ['C', 'Cpp', 'Cpp14', 'Java', 'Python', 'Python3', 'Scala', 'Php', 'Perl', 'Csharp']


def gfg_compile(lang, code, _input=None, save=False):
    data = {
      'lang': lang,
      'code': code,
      'input': _input,
      'save': save
    }
    r = requests.post(gfg_compiler_api_endpoint, data=data)
    return r.json()


if __name__ == "__main__":
    lang = 'Cpp14'
    code = """
    #include <iostream>
    using namespace std;
    int man() {
        it a, b;
        cin >> a >> b;
        cout << (a+b);
        return 0;
    }
    """
    _input = "1 5"
    print(gfg_compile(lang, code, _input))

【问题讨论】:

  • 抱歉,SO 不是免费的代码翻译服务。在docs 中查找如何执行此操作,尝试自己解决此问题,如果您陷入困境并用尽所有可用资源,请返回并相应地编辑您的问题,包括您的代码,我们很乐意为您提供帮助修复它。

标签: javascript python post python-requests http-post


【解决方案1】:

您可以使用简单的 xhr 请求。

var url = "https://example.com/user";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

var data = `{
  "Id": 78912,
  "Customer": "Jason Sweet",
  "Quantity": 1,
  "Price": 18.00
}`;

xhr.send(data);

【讨论】:

    【解决方案2】:

    您可以使用“axios”库。例如,

    axios.post('https:localhost:300/page', {
        var1: 'abcd',
        var2: '1234'
      })
      .then(function (response) {
        console.log(response);
      })
    

    您可以查看他们的文档,https://axios-http.com/。 有大量的 youtube 视频对其进行了彻底的解释。

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2020-10-28
      • 2013-09-24
      • 2013-10-06
      • 2015-02-28
      • 2017-02-13
      • 2021-11-30
      • 2017-05-03
      • 2017-10-30
      相关资源
      最近更新 更多