简体   繁体   English

如何正确实现 Express + Node JS + Browserify?

[英]How to implement Express + Node JS + Browserify properly?

So I'm somewhat new to the whole web development thing with node.js and I'm wondering if someone could help me out with understanding how to implement my application correctly.所以我对 node.js 的整个 web 开发工作有点陌生,我想知道是否有人可以帮助我了解如何正确实现我的应用程序。

So the app is a simple landing page with an email form that takes an email and sends it to the API.因此,该应用程序是一个简单的登录页面,带有 email 表单,该表单采用 email 并将其发送到 API。 I designed this functionality without issue except when I launched my website i'm getting a required not defined error.我设计了这个功能没有问题,除非当我启动我的网站时,我得到了一个必需的未定义错误。

I understand that this is because node.js is a server side technology so that when the application goes live, the client doesn't understand what required means.我知道这是因为 node.js 是一种服务器端技术,因此当应用程序上线时,客户端不明白所需的含义。

Through further research, I figured out that I had two options and that's to either implement synchronous dependencies via something like Browserify or take things asynchronously and use something like RequireJS.通过进一步的研究,我发现我有两种选择,一种是通过 Browserify 之类的东西实现同步依赖,另一种是异步处理并使用 RequireJS 之类的东西。

Right now I've decided on using Browserify, (unless someone can convince me otherwise) I just need help with figuring out how to implement it for my specific app.现在我决定使用 Browserify,(除非有人能说服我)我只需要帮助弄清楚如何为我的特定应用程序实现它。

app.js应用程序.js

//The dependenices my node js app needs (also where the require bug occurs)
//------------------------------------------------------------------------------------------------------------------------
const express = require('express'); //Require the express package that we installed with npm install express

const request = require('request'); //Require the express package that we installed with npm install request

const bodyParser = require('body-parser'); //Require the express package that we installed with npm install bodyParser

const path = require('path'); //Require the express package that we installed with npm install path
//------------------------------------------------------------------------------------------------------------------------



const app = express(); //Creates the application with express


//Middleware
app.use(express.json()); //Tells express to use JSON as it's input

app.use(bodyParser.urlencoded({ extended: false })); //Prevents XSS, only will return if the url has specified enconding

app.use(express.static(path.join(__dirname, '/site'))); //Tells the app to use the current path D:\Gaming Galaxy\Website\Website\main\site as the dir for the website

console.log("The directory used is", express.static(path.join(__dirname, '/site')));

app.post('/subscribe', (req, res) => { //Makes a post request to express req is the request and res is the response
    const { email, js } = req.body; //Create a constant that makes up of the request's body

    const mcData = { //Create a constant JSON object mcData, that contains the email from the above constant and a status message
        members: [
            {
                email_address: email,
                status: 'pending'
            }
        ]
    }

    const mcDataPost = JSON.stringify(mcData); //Turns the JSON object into a string

    const options = { //Sets a JSON object of a bunch of options that mailchimp will use
        url: 'https://us20.api.mailchimp.com/3.0/lists/f10300bacb',
        method: 'POST',
        headers: {
            Authorization: 'auth f24c3169da044653d1437842e39bece5-us20'
        },
        body: mcDataPost
    }

    if (email) { //If there's an email that exists
        request(options, (err, response, body) => { //Send a request to mail chimp
            if (err) { //If there's an error
                res.json({ error: err }) //Print said error
            } else { //If there's not an error
                if (js) {  //If javascript is enabled (boolean)
                    res.sendStatus(200); //Send a success message
                } else {
                    res.redirect('/success.html'); //If it's disabled, send them to a successful HTML page.
                }
            }
        })
    } else {
        res.status(404).send({ message: 'Failed' }) //If the email doesn't exist, have it fail
    }

});

app.listen(5000, console.log('Server started!')) //Console log that confirms the start of the server

package.json package.json

{
  "name": "gaminggalaxy",
  "version": "1.0.0",
  "main": "site/js/app.js",
  "dependencies": {
    "body-parser": "^1.19.0",
    "commonjs": "^0.0.1",
    "express": "^4.17.1",
    "index": "^0.4.0",
    "node-fetch": "^2.6.6",
    "prototype": "^0.0.5",
    "request": "^2.65.0",
    "requirejs": "^2.3.6",
    "uniq": "^1.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  },
  "scripts": {
    "serve": "node app",
    "dev": "nodemon app"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/InvertedTNT/Main.git"
  },
  "bugs": {
    "url": "https://github.com/InvertedTNT/Main/issues"
  },
  "homepage": "https://github.com/InvertedTNT/Main#readme",
  "description": ""
}

index.html (the form itself) index.html(表单本身)

<form action="/subscribe" method="POST">
   <div class="newsletter-form-grp">
        <i class="far fa-envelope"></i>
        <input type="email" name="email" id="email"
              placeholder="Enter your email..." required>
    </div>
    <button id="cta">SUBSCRIBE <i class="fas fa-paper-plane"></i></button>
</form>

folder structure文件夹结构

node_modules
site
  -index.html
  -css
  -js
     - app.js
  -images
app.js
package-lock.json
package.json

Thank you for your help, I would appreciate any sort of advice on how I can use those dependencies and the overall implementation of browserify.感谢您的帮助,我将不胜感激有关如何使用这些依赖项和 browserify 的整体实现的任何建议。

A browser is an HTTP client.浏览器是 HTTP 客户端。

Express is a framework for building HTTP servers. Express 是用于构建 HTTP 服务器的框架。

HTTP clients make requests to HTTP servers which then send responses back. HTTP 客户端向 HTTP 服务器发出请求,然后返回响应。

Express depends on Node.js. Express 依赖于 Node.js。 It requires features provided by Node.js (like the ability to listen for network requests) which are not available in browsers.需要Node.js 提供的功能(例如侦听网络请求的能力),这些功能在浏览器中不可用。

Browserify can bundle up JavaScript which is written using modules into non-module code that can run in a browser but only if that code does not depend on Node.js-specific features. Browserify 可以捆绑使用模块编写的 JavaScript 到可以在浏览器中运行的非模块代码中,前提是该代码依赖于 Node.js 特定的功能。 (ie if the JS modules are either pure JS or depend on browser-specific features). (即如果 JS 模块是JS 或依赖于浏览器特定的功能)。

Browserify cannot make Express run inside the browser. Browserify 无法让 Express 在浏览器中运行。


When you run your JS program using Node.js you can then type the URL to the server the program creates into the browser's address bar to connect to it.当您使用 Node.js 运行 JS 程序时,您可以将 URL 键入到程序创建的服务器到浏览器的地址栏中以连接到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM