首页 > 解决方案 > Router.post 未连接到 AJAX

问题描述

我正在尝试创建一个应用程序来转换温度。我在我的 temp.js 类中进行了 POST 调用,然后它应该调用我的 ajax.js 类来处理信息并执行计算以将我需要的结果返回给我。但是它从来没有进入我的 ajax 调用,所以我现在被卡住了。如果有人有任何建议或答案,请告诉我。temp.js

const express = require('express');
const path =  require('path');
const router = express.Router();
const app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.json({extended: false}));

router.get("/",function(req, res){
        res.sendFile(path.join(__dirname,"/tempConverter.html"));
    });
router.post("/ajaxTemp", function(req, res){
        console.log(req.body.data);
        console.log(req.headers['content-type']);
        var body = req.body;
        
        res.send(JSON.stringify(body));
    });
 
 
module.exports = router;

ajax.js

$(document).ready(function(){
    $("#tempForm").submit(function(e){
        e.preventDefault();
        var tempInput = $("#tempInput").val();
        var fromOp = $("#fromOp").val();
        var toOp = $("#toOp").val();

        if(fromOp !== toOp){
            if(fromOp === "Fahrenheit"){
                //F -> C
                if(toOp === "Celsius"){
                    var result = (tempInput - 32)*(5/9);
                }
                //F -> K
                else{
                    var result = (tempInput - 32)*(5/9)+273.15;
                }
            }else if(fromOp === "Celsius"){
                //C -> F
                if(toOp === "Fahrenheit"){
                    var result = (tempInput + 32)*(9/5)+273.15;
                }
                //C -> K
                else{
                    var result = tempInput + 273.15;
                }
            }else{
                //K -> C
                if(toOp === "Celsius"){
                    var result = tempInput - 273.15;
                }
                //K -> F
                else{
                    var result = (tempInput + 32)*(9/5)-273.15;
                }
            }
        }else{
            alert("Cannot convert Same Degree");
        }
        

        $.ajax({
            url :  "/ajaxTemp",
            data : {
                result
            },
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            success : function(res){
                console.log("made it here");
                $("#tempForm").append("<br/>"+res);
            }, error: function(err){
                console.log(err);
            }
        })
    })
}); 

.html 文件:

<html>
    <head>

    </head>

    <body>
      <h1>
        Lets convert some Temperatures
      </h1>
      <form id="tempForm" action="tempConverter/ajaxTemp" method="POST">
        <input id="tempInput" type="number">
        <select id="fromOp">
          <option id="fromF">Farenheit</option>
          <option id="fromC">Celsius</option>
          <option id="fromK">Kelvin</option>
        </select>
        Convert to:
        <select id="toOp">
          <option id="toF">Farenheit</option>
          <option id="toC">Celsius</option>
          <option id="toK">Kelvin</option>
        </select>
        <input type="submit" value="Submit">
      </form>
      
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</html>

上面的代码只是我正在创建的路线之一,我有一个应用程序从中输入的主类:

应用程序.js

const express = require('express');
const bodyParser = require('body-parser');
const path =  require('path');
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.listen(8080);


app.use("/tempConverter",require('./assets/Temperature/temp.js'));


标签: javascripthtmlnode.jsajaxexpress

解决方案


您的 html 工作正常。您的快速 API 出错。您忘记了要求 express 并错过了一些语法。

const express = require('express');
const router = express.Router();
const app = express();

// Remember to update ajax url at ajax.js file
const port = 8080;

// Your routes are here ...
router.get(...)
router.post(...)

app.use('/', router);

// If your run server local. 
// Your api url will be http://localhost:8080
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

推荐阅读