结合客户端jQuery和服务器-Side Express [英] Combining client-side jQuery and server - side Express

查看:45
本文介绍了结合客户端jQuery和服务器-Side Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Express/Node.我正在尝试构建一个简单的HTML form ,该模板可以验证客户端(例如,使用jQuery/AJAX),但我也可以从服务器端(使用Express.js)进行服务.需要明确的是,该应用程序现在非常简单,我可以可以在客户端执行所有操作,但是我想构建服务器端的操作来学习整个管道.

这是表格.注意名称为 change-color button 类型的 button ;这是我用于调试目的的 button ,稍后将进行解释.我还包括 jquery v.3.6.0和我自己的 client.js 文件.

 <!DOCTYPE html>< html lang ="en";dir ="ltr">< head><元字符集="utf-8">< title> A MWE</title>< link rel ="stylesheet"href =" styles.css"></head><身体>< h1>一种简单形式.< form action ="/"method ="post"><输入类型=文本";name ="num1"占位符=第一个数字"value =".< br><输入类型=文本";name ="num2"占位符=第二个数字";value =".< br>< button type =提交";名称=提交">计算</button>.< button type =按钮"名称=改变颜色">改变颜色</按钮>.</form>< script src =" https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"</script>< script src ="client.js"charset ="utf-8"</script></body></html> 

在表格中,用户应给我两个数字,然后服务器将它们相加并返回.服务器代码位于名为 server.js 的文件中,概述如下:

  const express = require("express");const bodyParser = require("body-parser");const app = express();app.use(bodyParser.urlencoded({extended:true}));app.listen(3000,()=> {console.log(服务器在端口3000上旋转.");});app.get("/",(req,res)=> {console.log(在根路由处服务GET请求.");res.sendFile(absoluteDirPath()+"index.html");});app.post("/",(req,res)=> {console.log(在根路由上服务POST请求.");const num1 = Number(req.body.num1);const num2 = Number(req.body.num2);res.send("h3"结果:"+(num1 + num2)+"/h3");});函数absoluteDirPath(){const path = require('path');返回__dirname + path.sep;} 

当我们第一次访问根端点(GET调用)时,服务器使用 res.sendFile()将上述HTML文件发送给用户.当用户在 form 上输入两个数字并单击 form 中类型为 submit button 时, server.js 方法的 app.post()计算并发送请求的金额.

很明显,在应用求和之前,我需要做一些验证.如果我没有电话号码怎么办?基于对

解决方案

您没有做错任何事情.这只是每个使用node.js的人(包括我在内)的常见问题!无法访问Node.js中的其他文件).

您必须告诉express客户端可以查看哪些文件.让我们创建一个名为 public 的文件夹.在文件夹内,放入 .js .css 文件,以及希望由客户端访问的其他图片或其他资产.

此网站上的公共文件夹将替换为您的域.考虑以下文件/文件夹:

  index.js(服务器)/意见-index.html/上市-style.css-client.js-jquery.min.js 

客户端只能访问 public 内部的文件,例如: http://localhost:3000/style.css http://localhost:3000/client.js http://localhost:3000/jquery.min.js .但是,除非服务器明确获取它,否则我们将无法访问其他文件(不在公共文件夹中):

  app.get('/index.html',function(req,res){res.sendFile(path.join(__ dirname,'/views/index.html'));}); 

解决方案:

 <代码>//...const path = require('path');const app = express();app.use(express.static(path.join(__ dirname,'/public')));//您在这里路由 

这样,客户端将能够访问 public 目录下的所有文件.您的问题应该得到解决.

请紧记::服务器仍然可以访问所有文件.这仅限制了客户端.

I'm learning Express / Node. I'm trying to build a simple HTML form which I validate client - side (e.g, with jQuery / AJAX) but I also serve from the server - side (with Express.js). To be clear, the app is now simple enough that I could do everything client - side, but I want to build server - side behavior to learn the entire pipeline.

Here's the form. Note the button of type button with name change-color; this is a button that I use for debugging purposes, explained later. I am also including jquery v.3.6.0 and my own client.js file.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>A MWE</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>A simple form.</h1>
    <form action="/" method="post">
      <input type="text" name="num1" placeholder = "First Number" value=""> <br>
      <input type="text" name="num2" placeholder = "Second Number" value=""> <br>
      <button type="submit" name="submit">Calculate</button>
      <button type="button" name="change-color">Change color</button>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="client.js" charset="utf-8"></script>
  </body>
</html>

In the form, the user is supposed to give me two numbers, which the server will then sum and return. Server code is inside a file called server.js, outlined below:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));

app.listen(3000, () => {
  console.log("Server spun on port 3000.");
});

app.get("/", (req, res) => {
  console.log("Serving a GET request at root route.");
  res.sendFile(absoluteDirPath() + "index.html");
});

app.post("/", (req, res) => {
  console.log("Serving a POST request at root route.");
  const num1 = Number(req.body.num1);
  const num2 = Number(req.body.num2);
  res.send("<h3>Result: " + (num1 + num2) + "</h3>");
});

function absoluteDirPath() {
  const path = require('path');
  return __dirname + path.sep;
}

When we first access the root endpoint (GET call), the server uses res.sendFile() to send the above HTML file to the user. When the user inputs two numbers on the form and clicks on the button of type submit inside the form, the app.post() of server.js method calculates and send()s the requested sum.

Clearly I need to do some validation before I apply the summation; what if I don't get a number? Based on the answers to this post, to avoid complex and sudden redirections, I seem to have to do this on the client side, e.g, in a separate .js file. In the same post, I have been advised to author something like the following function and assign it to an event listener:

function submitFormWithoutReloading() {
   $.ajax({
      type: "POST",
      url: "/",
      data: {
         num1: $('#idOfYourFirstInput').val(),
         num2: $('#idOfYourSecondInput').val()
      },
      success: function(res) {
         alert(res); // This is what the server returns
      }
   });
}

However, I seem to have stumbled upon a bigger issue here. I am having some trouble running all my jQuery when I serve the user with the HTML file from the app.get() method! It seems as if every time I access http://localhost:3000/, the HTML file is sent to me, but the linked client.js file is not read (and I am guessing that the same thing holds for jQuery).

To ensure that this is what my problem is, I temporarily forgot about the validation routine, made the change-color HTML button mentioned above and added some dummy code to client.js:

$(document).ready(function() {
  alert("Hi!");
});

$('button[name="change-color"]').click(function() {
  $("body").toggleClass("colored-background");
});

So the change-color button is used just to toggle the body element to have yellow as its background as per this CSS rule:

.colored-background {
  background-color: yellow;
}

If I open index.html from my filesystem, it all works just fine; jQuery and my client.js file are loaded, the alert() comes just fine, and the button works as intended. But when I access localhost:3000 and the GET endpoint serves the client with the HTML file, it's as if the DOM scanning does not read client.js and I can't do any client - side stuff, including my much desired validation!

Any ideas of what I'm doing wrong? I know I could do everything on the client side here, but I want to learn how to split the concerns on client side and server side. Server side might want to access a DB, the client can't do everything.

// Edit: If it helps, the Chrome console says some interesting things when I load localhost:3000:

解决方案

You didn't do anything wrong. This is just a common problem that everyone using node.js (including me! Cant access other files in Node.js).

You have to tell express which files can be viewed by the client. Let's create a folder called public. Inside your folder, put you .js and .css files, as well as other pictures or other assets you want accessible by the client side.

This folder, public, on your website will be replaced with your domain. Consider these files/folders:

index.js (server)
/ views
   - index.html
/ public
   - style.css
   - client.js
   - jquery.min.js

The client can only access the files inside public, like this: http://localhost:3000/style.css, or http://localhost:3000/client.js, or http://localhost:3000/jquery.min.js. However, we will not be able to access the other files (not in the public folder), unless the server explicitly gets it:

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

Solution:

// ...
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, '/public')));
// You routes here

This way, the client will be able to access all the files under the public directory. Your problem should be solved.

Keep in mind: The server can still access all the files. This only restricts the client side.

这篇关于结合客户端jQuery和服务器-Side Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆