简体   繁体   中英

Use sweetalert2 with node.js and express.js

I'm trying to use sweetalert2 in my project node and express.js plus the configuration is not successful I guess.

I am receiving the following message:

swal is not defined

ReferenceError: swal is not defined

My Settings

index.js

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

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

    Swal('Hello world!');

});

HTML

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

Package.json

{
  "name": "festiva",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "ejs": "~2.5.7",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "morgan": "~1.9.0",
    "mysql": "^2.16.0",
    "sweetalert2": "^7.28.4"
  }
}

If someone can guide...

SweetAlert2 appears to be a client-side library, but you're using it on the server in your example.

To get your example to work, and without getting to complicated, try the following:

HTML

<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
    <h1 class="text-center title-1"> Cad </h1>
    <button type="button" onclick="swal('Hello, world!')">
        Click me
    </button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.28.2/sweetalert2.all.min.js"></script>
</body>
</html>

The script tag will include the library on the client, and will eliminate the need for any node/express.

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