简体   繁体   中英

Router.post not connecting to AJAX

I am trying to create an application to convert Temperatures. I make a POST call in my temp.js class which should then call my ajax.js class to handle the information and perform calculations to return to me the result I need. However it never makes it to my ajax call so I am stuck now. If anyone has any advice or answers please let me know. 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 file:

<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>

This code above is just one of the routes I'm creating I have a main class where the app enters from:

app.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'));


Your html works fine. Error at your express API. You forgot to require express and missed some syntax.

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}!`));

This line below is wrong because your route will be /tempConverter/tempConverter instead of /tempConverter

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

Your code should modify as below.

// Write as this for best practice
const router = require('./assets/Temperature/temp.js');

app.use("/", router);

// This line must be after app.use
app.listen(8080);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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