How to use sweetalert in nodejs?

那年仲夏 提交于 2020-06-28 08:21:10

问题


I have a nodejs code given with html code, I want to show a sweet alert on client side,after process a function in nodejs?.

var express = require('express');
var router = express.Router();
const Swal = require('sweetalert2');

router.post('/add', function(req, res, next) {

    Swal('Hello world!');

});

<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
    <h1 class="text-center title-1"> Cad </h1>
    <form action="/add" method="post">
        <input type="submit" value="Save"/>
    </form>
</body>
</html>

回答1:


Here's the only way you can show a popup swal

var express = require('express');
var router = express.Router();

router.post('/add', function(req, res, next) {

   res.json("Hello world!")
});


<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
    <h1 class="text-center title-1"> Cad </h1>
    <form id="form" action="#" method="post">
        <input type="submit" value="Save"/>
    </form>
</body>
</html>
<script>

//import JQuery from script
//import swal script

$("#form").on("submit", function(e){
e.preventDefault();

$.ajax({
  url: "/add",
  method: "post"
}).done(d=>{
  swal(e.responseJSON);
});
})
</script>



回答2:


Here you can do using EJS

var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
   res.status(201).render('new', { isAdded : true } );
});

In HTML side

<% if (isAdded) { %>
 <script>
  Swal.fire(
     'Good job!',
     'Data saved',
     'success'
 )
</script>
<% } %>



回答3:


In order to deal with this, you can use query parameters.

So, Here is what you can do

On the server

var express = require('express');
var router = express.Router();
router.post('/login', (req, res)=>{
   res.redirect("/login?success=true&message=Logged In Successfully")
});

On the Client-Side (EJS)

    <script>
    var urlParams = new URLSearchParams(window.location.search);
    if(urlParams.has('success') && urlParams.get('success')){
    swal({
    title: "Failed",
    text: `${message}`, 
    icon: "error",
    button: "Okay",
    }).then(()=>{
        console.log(window.location.hostname)
    window.location.replace(window.location.origin + '/login');

    })
}

This will simply popup swal. And you can toggle the value of success to render error and success messages.



来源:https://stackoverflow.com/questions/56542357/how-to-use-sweetalert-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!