首页 > 解决方案 > 弹出窗口和 css 不能在 localhost 或服务器上工作?

问题描述

请教我如何将 CSS 连接到服务器。我在 youtube 上关注了两个教程,一个是使用 node.js 和 nodemailer。有了这个,我使用本地主机来运行我的网站,但是我在第二个教程中制作的 CSS 和 js(单击按钮时弹出)在本地主机上不起作用,但是当我单击 html 文件本身时。

这是因为教程适用于不同类型的网站吗?喜欢静态和动态?

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewpoint" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link href="style.css" rel="stylesheet" type="text/css" />
        <title>Document</title>
    </head>
    <body>
        <h1>Welcome to my App</h1>
        <form>
            <div>
                <label for="email">Sender's Email: </label>
                <input type="email" id="email" placeholder="Your Email"> <br>
            </div>
            <div>
                <label for="classNum">To whom: R</label>
                <input type="number" id="classNum" placeholder="class#" min="1" max="31"> <br>
            </div>
            <div>
                <label for="subject">Subject: </label>
                <input type="text" id="subject" placeholder="Subject"> <br>
            </div>
            <div>
                <label for="text">Letter: </label> <br>
                <textarea name="text" id="text" cols="30" rows="10"></textarea> <br>
            </div>
            <input type="submit" value="Submit" class="modal-button" data-modal-target="#modal">
            <div class="modal" id="modal">
                <div class="modal-header">
                    <div class="title">Letter Sent!</div>
                </div>
                <div class="modal-body">
                    Pressing this button will refresh the page.
                    <div><button data-close-button class="refresh-button">Send another letter</button></div>
                    
                </div>
            </div>
            <div id="overlay"></div>
        </form>

        <script src="script.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>

            $('form').on('submit', (e) => {
                e.preventDefault();

                const email = $('#email').val().trim();
                const subject = $('#subject').val().trim();
                const text = $('#text').val().trim();
                const classNum = $('#classNum').val().trim();

                const data = {
                    email,
                    subject,
                    text,
                    classNum
                };

                $.post('/email', data, function(){
                    console.log('Server received our data')
                });
            });;
        </script>
    </body>
</html>

这是 server.js

const express = require('express');

const sendMail = require('./mail')

const log = console.log;
const app = express();
const path = require('path');

const PORT = 8080;


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

app.post('/email', (req, res) => {
    const { subject, email, text, classNum} = req.body;
    console.log('Data: ', req.body);

    sendMail(email, subject, text, classNum, function(err, data){
        if (err){
            res.status(500).json({ message: 'Internal Error'});
        }
        else{
            res.json({ message: 'Email sent!' });
        }
    });
   // res.json({ message: 'Message received!' })
});



app.get('/', (req, res) =>{
    res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

app.listen(PORT, () => log('Server is starting on PORT: ', 8080));

这个是用于弹出窗口的,script.js

const openModalButtons = document.querySelectorAll('[data-modal-target]');
const closeModalButtons = document.querySelectorAll('[data-close-button]');
const overlay = document.getElementById('overlay');

var path = require('path') //from stackoverflow
app.use(express.static(path.join(__dirname, 'public')));

openModalButtons.forEach(button => {
    button.addEventListener('click', () => {
        const modal = document.querySelector(button.dataset.modalTarget)
        openModal(modal)
    })
})

closeModalButtons.forEach(button => {
    button.addEventListener('click', () => {
        const modal = button.closest('.modal')
        closeModal(modal)
    })
})


function openModal(modal) {
    if (modal == null) return
    modal.classList.add('active')
    overlay.classList.add('active')
}

function closeModal(modal) {
    if (modal == null) return
    window.open("https://www.w3schools.com");
}

请告诉我是否需要包含 CSS 和 mail.js 。

标签: javascriptnode.jspopuplocalhost

解决方案


如果您想允许用户或浏览器从您的服务器获取文件,您需要将它们添加到您的服务器端代码中。例如,您添加了对 的样式表引用index.html,因此浏览器将尝试/style.css从服务器获取该文件 ( )。您没有在服务器端对此进行任何引用,因此服务器将响应 404 Not Found 或其他错误。

为了使服务器响应对“ /style.css”的请求,您需要将以下内容添加到您的服务器端index.js

app.get("/style.css" /*name of file in index.html*/, (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'style.css')); //CHANGE THIS TO THE NAME OF THE FILE ON THE SERVER
});

您的浏览器脚本也需要这样做script.js

app.get("/script.js" /*name of file in index.html*/, (req, res) => {
    res.sendFile(path.join(__dirname, 'views', 'script.js'));
});

app.get告诉 express 响应第一个参数的 GET 请求:在示例中,即“ /style.css”。如果您想响应对“ /foobar”的 GET 请求,那么您将编写app.get("/foobar", (req, res) => {/*SOME CODE HERE*/});. 它不起作用的原因是当浏览器尝试查找时style.cssscript.js服务器不知道该怎么做,因为您没有包含app.get这些文件,因此响应错误。


由于其工作方式的架构,这可能会令人困惑。看这张图:

==== HOW A WEBSITE SENDS A FILE ====

 ______                ____              ______
/ .  . \  GET /file   [____]   READ    /       |
|   j  |   ======>    [____]  ======>  | file  |
\__===_/   <======    [____]  <======  |       |
  user     RESPONSE   server           |_______|

推荐阅读