Так что я пытаюсь развернуть простое приложение, подобное твиттеру, в HEROKU или MongoDB, и в настоящее время я тоже прибиваю. Для mongodb я получаю один из двух результатов: либо внутренняя ошибка сервера, либо фактический код, отображаемый в браузере вместо приложения. Поскольку у меня есть две отдельные папки для каждой реализации, я собираюсь опубликовать их позже.
MONGODB
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');
});
Клиент. 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'
});
}
сейчас. json
{
"name": "camitter-api",
"version": 2,
"builds": [
{
"src": "index.js",
"use": "@now/node-server"
}
],
"routes": [
{ "src": "/.*", "dest": "index.js" }
],
"env": {
"MONGO_URI": "@camitter-db"
}
}
и пакет. 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"
}
}
И это вывод терминала на реализацию. В настоящее время ссылка показывает «внутренняя ошибка сервера»
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
Здесь я уверен, что я делаю что-то не так с индексом. js или клиентом. js или обоими , Я видел тонны гидов и все необходимые файлы. При развертывании приложение просто не работает. Поскольку я действительно пытался адаптировать код для работы на Heroku, я почти уверен, что проблема заключается в самом коде. Это папка:
node_modules
.gitignore
index.js
package_lock.json
client.js
favicon.ico
index.html
loading.gif
styles.css
Procfile
Индекс. 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');
});
Клиент. 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
{
"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"
}
}
Я очень ценю любую помощь по развертыванию на любой из двух платформ, я пытаюсь извлечь максимальную пользу из этого карантина и пытаюсь решить эту проблему в течение двадцати часов подряд. Приветствую всех изолированных людей!