Home > Net >  CSS Not Rendering After A Post Submit Using Express
CSS Not Rendering After A Post Submit Using Express

Time:08-02

I was able to get the CSS loaded on the initial page of the get, but when I use a button to submit data using POST, The post works, but the CSS fails to load and the screen is just plain with post info. here is some info below

app.use(express.static(__dirname   "/public")); 

app.get('/', (req,res)=>{
    
    res.sendFile(__dirname   "/index.html")
})

The HTML

<form action="/" method="post">
    <input type="text" name="n1" placeholder="First Number">
    <input type="text" name="n2" placeholder="Second Number">
    <button type="submit" name="submit">Calculate</button>

</form>

The post

app.post("/",function(req,res){

    var num1 = Number(req.body.n1); 
    var num2 = Number(req.body.n2);

    var result = num1   num2;

    res.send("The result is "   result);
})

Page loads background color fine, but when I hit the calculate button is when CSS doesn't load. Just wondering what else I'd need to do to make CSS appear everywhere?

CodePudding user response:

On the initial GET request, aside from the form part, you are probably responding with a static html file that in turn references css files.

That's not the case when you hit the "Calculate" button. On that POST request you are responding with plain text ("The result is x"), not HTML, and that doesn't reference any styles whatsoever.

You may want to look into some templating engine like Handlebars, EJS, or something more flexible like Vue, Svelte, React or Angular.

CodePudding user response:

If you want to send a styled html file in your POST request, you need to use res.sendFile()

Your post request is only sending back the result with the number.

Because you need to specify absolute file paths, you should write it as below.

app.post("/",function(req,res){

    var num1 = Number(req.body.n1); 
    var num2 = Number(req.body.n2);

    var result = num1   num2;

    res.sendFile('public/index.html' , { root : __dirname});
})

This will get you the styled html, but you will need to write some JavaScript to change the html based on the output.

in jQuery, it might look like

$("h1").text("The result is ${result}");
  • Related