【问题标题】:Call a POST request from html or js file, Express从 html 或 js 文件 Express 调用 POST 请求
【发布时间】:2020-04-19 10:57:41
【问题描述】:

所以我刚开始第一次尝试使用 express 进行一些轻量级的后端开发。 我想从一个 html/js 文件中调用一个 POST 请求,我发现了如何使用 Jquery 来完成它。 但是我想知道你如何在纯 javascript 中做同样的事情。 这是我在 Jquery 中的代码:

---服务器---

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

const greens = {"orange"}

app.get("/greens", (req, res) => {
    res.json(greens);
});

app.post('/greens', (req,res) => {
  var itemName=req.body.itemName;
  console.log("name = "+itemName);
  res.end("yes");
});

app.listen(3000, "localhost", () => {
    console.log("the server is up and running! http://localhost:3000/greens");
});

---JS文件---

$(document).ready(function(){
    var itemName;
    $("#submit").click(function() {
        let Name = "banana";
        $.post("http://localhost:3000/login",{itemName: Name}, function(data){
        });
    });
});

ps。我拥有的 HTML 代码只是一个 ID 为“提交”的按钮。 pps。我知道代码并没有真正做任何事情,但我只想知道如何将 jquery 转换为 javascript,仅此而已。

使用 fetch 解决了!

    fetch("http://localhost:3000/login",
{
    method: "POST",
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({itemName: "user"})
});

【问题讨论】:

    标签: jquery express server backend


    【解决方案1】:

    有两种方法可以做到这一点。这取决于您是要使用 ES5 还是 ES6 及更高版本。

    对于 ES5 试试看这里,解释的很好:https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

    对于 ES6,您可以使用 fetch-API:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    希望本教程对您有所帮助!

    【讨论】:

      【解决方案2】:

      jQuery代码可以翻译成以下纯JS代码:

      document.getElementById("submit").addEventListener("click", () => {
          let xmlHttp = new XMLHttpRequest();
          let Name = "banana";
      
          xmlHttp.open("post", "http://localhost:3000/login", true);
          xmlHttp.setRequestHeader("Content-Type", "application/json");
          xmlHttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
          xmlHttp.send(JSON.stringify({itemName: Name}));
      });
      

      至于文档准备部分,您可以在这里找到它的纯实现: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

      【讨论】:

      • 但是当我发送它时,我只会得到 undefined o.o document.getElementById("submit").addEventListener("click", () => { let xmlHttp = new XMLHttpRequest(); Name="香蕉"; xmlHttp.open("post", "localhost:3000/greens"); xmlHttp.send({itemName: Name}); });
      • 我仍然得到 undefined o.o
      • 请立即尝试,将其更改为 AJAX 请求,现在应该可以了。
      • 现在我得到“xmlhttp 未定义”xD 但我设法用 fetch 解决了它:) 非常感谢您抽出宝贵的时间!
      • 不客气,没有定义 xmlhttp 是因为我不小心写了 xmlhttp 而不是 xmlHttp。
      【解决方案3】:

      希望这会对您有所帮助。根据您的要求使用。

      服务器

      const express = require('express');
      const cors = require('cors')
      const app = express();
      app.use(express.json());
      app.use(express.urlencoded({extended: true}));
      app.use(cors())
      const port = 3000;
      
      app.get('/', (req, res) => {
          res.send('Hello world');
      });
      
      app.post('/greens', (req, res) => {
          const body = req.body;
          console.log('BODY', body);
          res.json(body);
      });
      
      app.listen(port, ()=>{
          console.log(`Listening to ${port}`);
      })
      

      前端代码:

      $(document).ready(function(){
          const item = $('#item');
          const submit = $('#handleSubmit');
          submit.click((e)=>{
              e.preventDefault();
              let fruitName = item.val();
              debugger;
              $.post( "http://localhost:3000/greens", { itemName: fruitName })
              .done(function( data ) {
                alert( "Data Loaded: " + data );
              });
          })
      })
      

      HTML

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Document</title>
          <script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
          <script src="main.js"></script>
      </head>
      <body>
          <form>
              <input type="text" id="item" value="" name="item"/>
              <button type="submit" id="handleSubmit">Submit</button>
          </form>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2019-11-04
        • 2015-06-26
        • 2015-07-05
        • 2014-01-27
        • 1970-01-01
        • 2022-01-25
        • 2018-07-08
        • 2016-11-14
        • 2018-02-10
        相关资源
        最近更新 更多