简体   繁体   English

无法将简单的 node.js 应用程序部署到 heroku 或 MongoDB

[英]Can't deploy simple node.js app to heroku nor MongoDB

So im trying to deploy a simple twitter like app to HEROKU or MongoDB and i'm currently nailing either.所以我试图将一个简单的 twitter 之类的应用程序部署到 HEROKU 或 MongoDB 并且我目前正在搞定。 For mongodb I get one out of two outcomes, either a internal server error or the actual code displaying on the browser instead of the app.对于 mongodb,我得到了两种结果中的一种,一种是内部服务器错误,另一种是显示在浏览器而不是应用程序上的实际代码。 Since I have two separate folders for each implementation i'm going to post subsequently.由于每个实现我都有两个单独的文件夹,因此我将随后发布。

MONGODB MONGODB

Index.js (This is the server side node code) Index.js(这是服务器端节点代码)

const express = require('express');
//Cors permite que cualquiera se comunique con el server.
const cors = require('cors');
const monk = require('monk');
const Filter = require('bad-words');
const rateLimit = require('express-rate-limit');

const filter = new Filter();
const app = express();
const db = monk(process.env.MONGO_URI || 'localhost/meower');
const mews = db.get('mews');

//ORDER MATTERS, WHAT IS FIRST GETS EXECUTED FIRST
app.enable('trust proxy');
app.use(cors());
//any incoming request that is JSON will pass
app.use(express.json());



//server, when you get a request run this function.
app.get('/',(request,response) => {
  res.json({
    message: 'Meower!'
  });
});

app.get('/mews', (req,res) => {
  mews
    .find()
    .then(mews => {
      res.json(mews);
    });
});

function isvalidmew(mew){
  return mew.name && mew.name.toString().trim() !== '' &&
    mew.content && mew.content.toString().trim() !== '';
}

//limit the submit rate

app.use(rateLimit({
  windowMs: 30 * 1000,
  max: 2
}));

//this will wait for incoming data and insert in database
app.post('/mews', (req,res) => {
  if(isvalidmew(req.body)){
    const mew = {
      name: filter.clean(req.body.name.toString()),
      content: filter.clean(req.body.content.toString()),
      created: new Date()
    };

    mews
    .insert(mew)
    .then(createdMew => {
      res.json(createdMew);
    });
  } else {
    res.status(422);
    res.json({
      message:'Hey! Name and Content are required!'
    });
  }
});

//abre el server en el puerto 5000

app.listen(5000, () => {
  console.log('Listening on http://localhost:5000');
});

Client.js客户端.js

const form = document.querySelector('form');
const loadingElement = document.querySelector('.loading');
const mewsElement = document.querySelector('.mews');
const API_URL = 'http://localhost:5000/mews';

loadingElement.style.display = '';

console.log('hola')

listallmews();

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const formData = new FormData(form);
  //We grab the stuff from the form
  const name = formData.get('name');
  const content = formData.get('content');
  //We put it in an object
  const mew = {
    name,
    content
  };
  //We send the data to the server
  form.style.display = 'none';
  loadingElement.style.display = '';

  fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(mew),
    headers : {
      'content-type':'application/json'
    }
  }).then(response => response.json())
    .then(createdMew => {
      form.reset();
      setTimeout(() => {
        form.style.display = '';
      },30000);
      listallmews();
    });
});

function listallmews(){
  mewsElement.innerHTML = '';
  fetch(API_URL)
    .then(response => response.json())
    .then(mews => {
      console.log(mews);
      mews.reverse();
      mews.forEach(mew =>{
        const div = document.createElement('div');

        const header = document.createElement('h3');
        header.textContent= mew.name

        const contents = document.createElement('p')
        contents.textContent= mew.content;

        const date = document.createElement('small');
        date.textContent = new Date(mew.created);

        div.appendChild(header);
        div.appendChild(contents);
        div.appendChild(date);

        mewsElement.appendChild(div);
      });
    loadingElement.style.display = 'none'  
    });
}

now.json现在.json

{
  "name": "camitter-api",
  "version": 2,
  "builds": [
    {
      "src": "index.js",
      "use": "@now/node-server"
    }
  ],
  "routes": [
    { "src": "/.*", "dest": "index.js" }
  ],
  "env": {
    "MONGO_URI": "@camitter-db"
  }
}

and package.json和 package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "CJ R. <cj@null.computer> (https://w3cj.now.sh)",
  "license": "MIT",
  "dependencies": {
    "bad-words": "^1.6.3",
    "cors": "^2.8.4",
    "express": "^4.16.3",
    "express-rate-limit": "^3.1.1",
    "monk": "^6.0.6",
    "morgan": "^1.9.1"
  },
  "devDependencies": {
    "nodemon": "^1.18.4"
  }
}

And this is the terminal output on implementation.这是终端 output 上的实现。 Currently the link shows "internal server error"目前链接显示“内部服务器错误”

Alejandro@DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ now secrets add camisite mongodb+srv://alenieto:myactualpassword@camisite-irtu2.mongodb.net/test?retryWrites=true&w=majority
[1] 444
Alejandro@DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ Now CLI 18.0.0
Success! Secret camisite added under alenieto97 [709ms]        
$ now -e MONGO_URI=@camisite
Now CLI 18.0.0
? Set up and deploy “~\Desktop\Programacion\Meower”? [Y/n] y
? Which scope do you want to deploy to? Alejandro Nieto
? Found project “alenieto97/meower”. Link to it? [Y/n] n
? Link to different existing project? [Y/n] n
? What’s your project’s name? camisite
? In which directory is your code located? ./
No framework detected. Default project settings:
- Build Command: `npm run now-build` or `npm run build`
- Output Directory: `public` if it exists, or `.`
�  Inspect: https://zeit.co/alenieto97/camisite/ei55o9z4q [2s]
✅  Production: https://camisite.now.sh [copied to clipboard] [5s]
�  Deployed to production. Run `now --prod` to overwrite later (https://zeit.ink/2F).
�  To change the domain or build command, go to https://zeit.co/alenieto97/camisite/settings
[1]+  Done                    now secrets add camisite mongodb+srv://alenieto:lapata97@camisite-irtu2.mongodb.net/test?retryWrites=true

Alejandro@DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower
$ cd server

Alejandro@DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower/server
$ now -e MONGO_URI=@camisite
Now CLI 18.0.0
❗️  The `name` property in now.json is deprecated (https://zeit.ink/5F)
�  Inspect: https://zeit.co/alenieto97/camitter/6b76zrggu [3s]
✅  Preview: https://camitter.alenieto97.now.sh [copied to clipboard] [20s]
�  To deploy to production (camitter.now.sh), run `now --prod`
❗️  Zero-configuration deployments are recommended instead of a `builds` property in `now.json`. The "Build and Development Settings" in your Project will not apply.

Alejandro@DESKTOP-LOJH5G7 MINGW64 ~/Desktop/Programacion/Meower/server

HEROKU HEROKU

Here i'm pretty sure im doing something wrong on the index.js or client.js or both.在这里,我很确定我在 index.js 或 client.js 或两者上都做错了。 I saw tons of guides and have all the files necesary.我看到了大量的指南,并拥有所有必要的文件。 When I deploy, the app simply doesn't work.当我部署时,该应用程序根本无法工作。 Since I actually tried to adapt the code to work on Heroku I'm pretty sure the problem lies in the code itself.因为我实际上试图调整代码以在 Heroku 上工作,所以我很确定问题出在代码本身上。 This is The folder:这是文件夹:

   node_modules
  .gitignore
   index.js
   package_lock.json
   client.js
   favicon.ico
   index.html
   loading.gif
   styles.css
   Procfile

Index.js索引.js

const express = require('express');
//Cors permite que cualquiera se comunique con el server.
const cors = require('cors');
const Filter = require('bad-words');
const rateLimit = require('express-rate-limit');
const { Pool, Client } = require('pg');
const port = process.env.PORT;

const connectionString = 'postgres://gvvsunuvtdhxpq:e9d3239ab17ea6f38d0b6303dee62b7704b37574e5eb2783ca7edb868cc7192a@ec2-18-235-20-228.compute-1.amazonaws.com:5432/d7df9kofqifk5b'
const pool = new Pool({
  connectionString: connectionString,
})

const filter = new Filter();
const app = express();

//ORDER MATTERS, WHAT IS FIRST GETS EXECUTED FIRST
app.enable('trust proxy');
app.use(cors());
//any incoming request that is JSON will pass
app.use(express.json());

//server, when you get a request run this function.
app.get('/',(request,response) => {
  res.json({
    message: 'Meower!'
  });
});

app.get('/mews', async (req, res) => {
    try {
      const client = await pool.connect()
      const result = await client.query('SELECT * FROM test_table');
      const results = { 'results': (result) ? result.rows : null};
      res.render('pages/mews', results );
      client.release();
    } catch (err) {
      console.error(err);
      res.send("Error " + err);
    }
  })

function isvalidmew(mew){
  return mew.name && mew.name.toString().trim() !== '' &&
    mew.content && mew.content.toString().trim() !== '';
}

//limit the submit rate

app.use(rateLimit({
  windowMs: 30 * 1000,
  max: 2
}));

//this will wait for incoming data and insert in database
app.post('/mews', (req,res) => {
  if(isvalidmew(req.body)){
    const mew = {
      name: filter.clean(req.body.name.toString()),
      content: filter.clean(req.body.content.toString()),
      created: new Date()
    };

    mews
    .insert(mew)
    .then(createdMew => {
      res.json(createdMew);
    });
  } else {
    res.status(422);
    res.json({
      message:'Hey! Name and Content are required!'
    });
  }
});


app.listen(port, () => {
  console.log('Listening on PORT');
});

Client.js客户端.js

const form = document.querySelector('form');
const loadingElement = document.querySelector('.loading');
const mewsElement = document.querySelector('.mews');
const API_URL = 'https://camisite.herokuapp.com/mews';

loadingElement.style.display = '';


listallmews();

form.addEventListener('submit', (event) => {
  event.preventDefault();
  const formData = new FormData(form);
  //We grab the stuff from the form
  const name = formData.get('name');
  const content = formData.get('content');
  //We put it in an object
  const mew = {
    name,
    content
  };
  //We send the data to the server
  form.style.display = 'none';
  loadingElement.style.display = '';

  fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(mew),
    headers : {
      'content-type':'application/json'
    }
  }).then(response => response.json())
    .then(createdMew => {
      form.reset();
      setTimeout(() => {
        form.style.display = '';
      },30000);
      listallmews();
    });
});

function listallmews(){
  mewsElement.innerHTML = '';
  fetch(API_URL)
    .then(response => response.json())
    .then(mews => {
      console.log(mews);
      mews.reverse();
      mews.forEach(mew =>{
        const div = document.createElement('div');

        const header = document.createElement('h3');
        header.textContent= mew.name

        const contents = document.createElement('p')
        contents.textContent= mew.content;

        const date = document.createElement('small');
        date.textContent = new Date(mew.created);

        div.appendChild(header);
        div.appendChild(contents);
        div.appendChild(date);

        mewsElement.appendChild(div);
      });
    loadingElement.style.display = 'none'  
    });
}

Procfile档案

web: node index.js

Package.json Package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "CJ R. <cj@null.computer> (https://w3cj.now.sh)",
  "license": "MIT",
  "dependencies": {
    "bad-words": "^1.6.3",
    "cors": "^2.8.5",
    "express": "^4.16.3",
    "express-rate-limit": "^3.1.1",
    "monk": "^6.0.6",
    "morgan": "^1.9.1",
    "pg": "^7.18.2"
  },
  "devDependencies": {
    "nodemon": "^1.18.4"
  }
}

I appreciate a lot any help to deploy on any of the two platforms, im trying to make the most out of this quarantine and have been trying to solve this for twenty hours straight.我非常感谢在这两个平台上部署的任何帮助,我试图充分利用这个隔离区,并且已经连续 20 小时尝试解决这个问题。 Cheers to any isolated folks!为任何孤立的人干杯!

Change index.js file更改 index.js 文件

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Our app is running on port ${ PORT }`);
});

You can also refer https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error您也可以参考https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

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

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