Mongo Atlas & Heroku & mailchimp - Newsletter Project


Posted by pei_______ on 2022-06-20

筆記重點

  1. static file(將css, img檔至入 'public'資料夾)
    app.use(express.static("public"));

  2. 修改html中連結至: relative path to public
    <link href="css/styles.css" rel="stylesheet">

  3. 上傳web & database平台: Mongo Atlas & Heroku


Mongo Atlas - Mongo DB 上傳


01. Update database route

mongoose.connect("mongodb+srv://<user_name>:<password>@cluster0.38dilgf.mongodb.net/todolistDB")

heroku - web / app 上傳 (Documentation)


00. Set up & Login & Check version

$ heroku login
$ node --version
$ npm --version
$ git --version

01. Track your codebase in a Git repository

$ git init
$ git add .
$ git commit -m "first commit"

02. Add a Heroku Git remote

$ heroku create
$ git push heroku master

03. Add a Procfile

$ touch Procfile

// in Procfile
> web: node app.js

04. Listen on the correct port

// in app.js
> app.listen(process.env.PORT || 3000, function() {
  console.log("sever is running.")
})

05. Specify the version of node

$ node --version

// in package.json
> "engines": {
    "node": "16.15.1"
  },

06. Create .gitignore and push

$ touch .gitignore
$ attrib +h .gitignore

// in .gitignore
/node_modules
npm-debug.log
.DS_Store
/*.env

$ git add . 
$ git commit -m "Add gitignore, procfile and update ports"
$ git push heroku master

FOR upload failed to check

$ heroku logs

FOR reupload the update version

$ git add .
$ git commit -m "update version"
$ git push heroku master

mailchimp - 管理訂閱名單 (Documentation)


01. Install & Set up

$ npm install @mailchimp/mailchimp_marketing

const mailchimp = require("@mailchimp/mailchimp_marketing");

mailchimp.setConfig ({
  apiKey: YOUR API KEY,
  server: YOUR SERVER ex.us11
})

02. Add a contact to an audience (Node.js)

const subscribingUser = {
  firstName: "TEST",
  lastName: "TEST",
  email: "test123@example.com"
};

async function run() {
  const response = await mailchimp.lists.addListMember(listId, {
    email_address: subscribingUser.email,
    status: "subscribed",
    merge_fields: {
      FNAME: subscribingUser.firstName,
      LNAME: subscribingUser.lastName
    }
  });

  console.log("Successfully added contact as an audience member");
}

Nesletter Project


app.js

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

// 00. remember to install it 
// $ npm install @mailchimp/mailchimp_marketing
const mailchimp = require("@mailchimp/mailchimp_marketing")

// 01. set up mailchimp library
mailchimp.setConfig({
  apiKey: YOUR API KEY,
  server: YOUR SERVER ex.us11
})

// 02. static file (將css, img檔至入 'public'資料夾)
app.use(express.static("public"))

app.use(bodyParser.urlencoded({
  extended: true
}));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/sign.html")
})

app.post("/", function(req, res) {
  const firstName = req.body.fname;
  const lastName = req.body.lname;
  const email = req.body.email;
  const listID = YOUR LIST ID

  async function run() {
    try {
      const response = await mailchimp.lists.addListMember(listID, {
        email_address: email,
        status: "subscribed",
        merge_fields: {
          FNAME: firstName,
          LNAME: lastName
        }
      });
      res.sendFile(__dirname + "/success.html")
      console.log("success")
    } catch (e) {
      res.sendFile(__dirname + "/failure.html")
      console.log("fail")
    }
  }

  run();
})

// 03. 返回上一個頁面
app.post("/failure", function(req, res){
  res.redirect("/");
})

// 04. 上傳heroku前置作業(聆聽heroku指定頻道或3000)
app.listen(process.env.PORT || 3000, function() {
  console.log("sever is running.")
})

sign.html


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.98.0">
    <title>Newletter Signup</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.2/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.2/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.2/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.2/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.2/assets/img/favicons/safari-pinned-tab.svg" color="#712cf9">
<link rel="icon" href="/docs/5.2/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#712cf9">

    <!-- 上傳前修改: relative path to public -->
    <link href="css/styles.css" rel="stylesheet">
  </head>

  <body class="text-center">

<main class="form-signin w-100 m-auto">
  <form action="/" method="post">

    <!-- 上傳前修改: relative path to public -->
    <img class="mb-4" src="image\pennyLOGO.png" alt="" width="72" height="72">
    <h1 class="h3 mb-3 fw-normal">Signup to Newsletter</h1>

      <input type="text" name="fname" class="form-control top" placeholder="First Name">
      <input type="text" name="lname" class="form-control middle" placeholder="Last Name">
      <input type="email" name="email" class="form-control bottom" placeholder="email">
    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign Me Up</button>

    <p class="mt-5 mb-3 text-muted">&copy; Penny Newsletter</p>
  </form>
</main>

  </body>
</html>

Success.html

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Success</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-5">
      <h1 class="display-5 fw-bold">Great!</h1>
      <p class="col-md-8 fs-4">You've been successfully signed up to the newsletter, look forwards to lots of awesome content!</p>
    </div>
  </div>
</body>

</html>

failure.html

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Failure</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-5">
      <h1 class="display-5 fw-bold">Uh oh!</h1>
      <p class="col-md-8 fs-4">There are some problem. Please try again or contact the developer!</p>

    <form action="/failure" method="post">
      <button class="btn btn-lg btn-warning" type="submit" name="button">Try Again!</button>      
    </form>

    </div>
  </div>
</body>

</html>

#mongo #Heroku #web系列







Related Posts

【JS幼幼班】Step.05 基本語法:基本型別(空值、boolean、number)

【JS幼幼班】Step.05 基本語法:基本型別(空值、boolean、number)

[Alpha Camp] 學期2-1 回顧

[Alpha Camp] 學期2-1 回顧

Express template engine - Handlebars 功能

Express template engine - Handlebars 功能


Comments