I'm getting this cannot GET error whenever I run my app on a live server with VS Code. My best guess is that it has to do with my routing being incorrect, I'm just not sure what about my routing is wrong. Any sort of help is appreciated <3
The goal is to send a POST request with the user's email inputted into a form element when the app is finished.
app.js
const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
//Middleware
app.use(express.json());
app.use(bodyParser.urlencoded({extended: false}));
console.log("The directory is:", (path.join(__dirname, '/site')));
app.use(express.static(path.join(__dirname, '/site')));
app.post('/', (req, res) => {
console.log('hey!');
});
app.listen(5000, console.log('Server started!'))
landing.html
<form action="/subscribe" method="POST">
<div class="newsletter-form-grp">
<i class="far fa-envelope"></i>
<input name="email" id="email" required pattern="[a-z0-9.%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" type="email" placeholder="Enter your email...">
</div>
<button id="cta">SUBSCRIBE <i class="fas fa-paper-plane"></i></button>
</form>
JS Code inside landing.html
<script>
//form submission
let cta = document.getElementById('cta');
let email = document.getElementById('email').value;
let status = document.getElementById('status');
cta.addEventListener('click', (event) => {
event.preventDefault();
if(this.email.value == null || this.email.value == "") {
status.classList.add('statusShow');
} else {
let fetchData = {
method: 'POST',
body: JSON.stringify({email: this.email.value, js: true}),
headers: {"Content-Type": "application/json"}
}
fetch('/subscribe', fetchData)
.then(res => {
if(res.ok) {
// yay
} else {
status.classList.add('statusShow');
}
})
}
});
</script>
JSON Package
{
"name": "Main",
"version": "1.0.0",
"description": "",
"main": "site/js/app.js",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"index": "^0.4.0",
"request": "^2.88.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
},
"scripts": {
"serve": "node app",
"dev": "nodemon app"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Project Tree: https://imgur.com/a/B9Ucrap
Your landing.html is a static file (in the site folder?), and you also do not have a GET route defined in Express to serve this page. So, in order to access it from your browser, you need to use: http://localhost:5000/landing.html.
Your form says: <form action='/subscribe' action='POST'>. Therefore, your Express needs this route defined:
app.post("/subscribe", (req, res) => {
console.log("hey!");
res.send("got it!");
});
BTW, your Html doesn't have an element with id of status. Your subscribe button click event code will hit an error.
Related
I'm using MERN Stack and everything was working fine until I made some changes to the UI (Moving code to different components, changing styles,...).
I didn't change any code in the Axios request and only this POST request doesn't work, the other requests work normally.
I have already setup CORS in my backend
I can access my-project.herokuapp.com/insert link and there's no error in the Heroku logs. No error thrown in the client or server terminal.
When I click on the Add To List button in the form, the addToList function which contains the Axios POST request doesn't send the data to the database like it used to.
After 30 seconds - this error appears:
Please help me understand what is going on and how to fix this. I have looked for other solutions but I don't know how to apply to my case.
Thank you! :)
Here's my code:
addToList function on the client-side:
const [foodName, setFoodName] = useState('')
const [isVegetarian, setIsVegetarian] = useState('')
const [priceRange, setPriceRange] = useState('$')
const [foodUrl, setFoodUrl] = useState('')
const [foodList, setFoodList] = useState([])
const addToList = async (event) => {
event.preventDefault()
try {
await Axios.post(
"https://my-project.herokuapp.com/insert",
{
foodName: foodName,
isVegetarian: isVegetarian,
priceRange: priceRange,
foodUrl: foodUrl,
}
)
.then(() => {
setFoodName('')
setIsVegetarian('')
setPriceRange('$')
setFoodUrl('')
})
} catch(err) {
console.error(`The error is ${err}`)
}
}
Dinner.js - Mongoose Schema
const mongoose = require('mongoose')
const DinnerSchema = new mongoose.Schema({
foodName: {
type: String,
required: true,
},
isVegetarian: {
type: String,
required: true,
},
priceRange: {
type: String,
required: true,
},
foodUrl: {
type: String,
required: true,
}
})
const Dinner = mongoose.model("dinners", DinnerSchema)
module.exports = Dinner
Server's index.js and the endpoint that doesn't work:
const express = require("express")
const mongoose = require("mongoose")
const cors = require('cors')
const app = express()
require("dotenv").config()
const DinnerModel = require('./models/Dinner')
app.use(express.json())
app.use(cors())
// Connect to MongoDB
mongoose.connect(
'mongodb+srv://linktoDB',
{
useNewUrlParser: true,
}
)
// Create:
app.post("/insert", async (req, res) => {
const foodName = req.body.foodName
const isVegetarian = req.body.isVegetarian
const priceRange = req.body.priceRange
const foodUrl = req.body.foodUrl
const dinner = new DinnerModel(
{
foodName: foodName,
isVegetarian: isVegetarian,
priceRange: priceRange,
foodUrl: foodUrl
}
)
try {
await dinner.save()
res.send("Inserted successfully")
} catch(err) {
console.log(err)
}
})
// Creating a port:
app.listen(process.env.PORT || 3001, () => {
console.log("Server is connected.")
})
My backend's package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "12.20.1"
},
"scripts": {
"start": "node index.js",
"devStart": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.3",
"nodemon": "^2.0.15",
"validator": "^13.7.0"
}
}
UPDATE 1
I added this code and it still doesn't work:
const corsOptions = {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
}
app.use(cors(corsOptions))
Here's the preflight request and response when I try to add the document. One with status 204 and one with status 503:
https://i.stack.imgur.com/v1IcS.png
https://i.stack.imgur.com/AzH8d.png
UPDATE 2
I found out what the problem is when I check the payload. Please check my answer below.
Thanks everyone for helping me with this!
I have found what caused the 503 Error when checking for the Payload of the POST request in the Network tab.
It was receiving an empty string for my isVegetarian value.
That empty string happened because I changed the isVegetarian schema type from Boolean to String but forgot to change the initial state to a specific value:
const [isVegetarian, setIsVegetarian] = useState('')
In the Schema, I set isVegetarian to required: true so it won't accept empty strings.
-> So if you have the CORS config right and still have the same 503 error. Maybe check for the Network tab for preflight requests, response & payload to see if there's any leftover code you need to review.
Here is my code and file structure
In the /comments page when you click on the details link and it goes to the Edit page, then when you click on Edit comment, and it takes you to the edit page you can edit the comment but once you click on save, it goes back to /comment but the edit comment and the original comment is gone. Not sure what is wrong with my logic in the code?
node_modules
views/comments
edit.ejs
index.ejs
new.ejs
show.ejs
index.js
package-lock.json
package.json
package.json
{
"name": "practicerest",
"version": "1.0.0",
"description": "Practice ",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Manny Verma",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1",
"method-override": "^3.0.0",
"uuid": "^8.3.2"
}
}
edit.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit</title>
</head>
<body>
<h1>Edit</h1>
<form method="POST" action="/comments/<%=comment.id%>?_method=PATCH">
<textarea name="listing" id="" cols="30" rows="10"><%= comment.comment %> </textarea>
<button>Save</button>
</form>
</body>
</html>
index.js
const { urlencoded } = require('express');
const express = require('express');
const app = express();
const path = require('path');
const { v4: uuid } = require('uuid');
const methodOverride = require('method-override');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(methodOverride('_method'))
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
let comments = [{
id: uuid(),
username: 'Todd Barkley',
comment: 'Alright movie!!!!'
},
{
id: uuid(),
username: 'David Smith',
comment: 'Oh my that was a weird movie'
},
{
id: uuid(),
User: 'Erick Jones',
comment: 'Terrible movie, I walked out half way through it.'
}
]
//comments
app.get('/comments', (req, res) => {
res.render('comments/index', { comments });
})
//new
app.get('/comments/new', (req, res) => {
res.render('comments/new');
})
app.post('/comments', (req, res) => {
const { username, comment } = req.body;
comments.push({ username, comment, id: uuid() })
res.redirect('/comments');
})
//show
app.get('/comments/:id', (req, res) => {
const { id } = req.params;
const comment = comments.find(l => l.id === id);
res.render('comments/show', { comment });
})
//Edit
app.get('/comments/:id/edit', (req, res) => {
const { id } = req.params;
const comment = comments.find(l => l.id === id);
res.render('comments/edit', { comment });
})
// updating
app.patch('/comments/:id', (req, res) => {
const { id } = req.params;
const newCommentText = req.body.comment;
const foundComment = comments.find(l => l.id === id);
foundComment.comment = newCommentText;
res.redirect('/comments');
})
//delete
app.delete('/comments/:id', (req, res) => {
const { id } = req.params;
comments = comments.filter(l => l.id !== id);
// filter is a boolean function, for whatever the call back returns true for those elements will be added to the filter array, you want to try to not mutate an array you should make a copy and make a change to the copy of the array that's what comment.filter is doing, it's returning a new array
res.redirect('/comments');
})
app.listen(4000, () => {
console.log("On port 4000")
})
I think you should be using app.put() instead of app.patch()
app.put('/comments/:id', (req, res) => {
const { id } = req.params;
const newCommentText = req.body.comment;
const foundComment = comments.find(l => l.id === id);
foundComment.comment = newCommentText;
res.redirect('/comments');
})
I am new to node.js (just few days in) and am learning through a tutorial from youtube (don't know if it's allowed to post a link or not).
I am trying to create a database in couchDB. Everything works fine but as soon as I try to enter any details on the form, it displays the exception "Error creating Database Address" (Address is the name of the database I am trying to create)
I followed the tutorial very carefully and have been searching for a solution for a while now but end up with nothing.
Please help if you found something.
App.js:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var urlencoded = require('url');
var bodyParser = require('body-parser');
var json = require('json');
var logger = require('logger');
var methodOverride = require('method-override');
var nano = require('nano')('http://admin:password#localhost:5984');
var db = nano.use('address');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views',path.join(__dirname,'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
// app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/',routes.index);
app.post('/createdb', function(req, res) {
nano.db.create(req.body.dbname, function(err){
if(err) {
res.send("Error creating Database " + req.body.dbname);
return;
}
res.send("Database " + req.body.dbname + "created successfully");
});
});
app.post('/new_contact', function(req, res) {
var name = req.body.name;
var phone = req.body.phone;
db.insert({name : name, phone : phone, crazy : true}, phone, function(err,body, header) {
if(err) {
res.send("Error creating contact");
return;
}
res.send("Contact created successfully");
});
});
app.post('/view_contact', function(req, res) {
var alldoc = "Following are the contacts";
db.get(req.body.phone, {revs_info : true}, function(err, body) {
if(!err) {
console.log(body);
}
if(body) {
alldoc += "Name: " + body.name + "<br/>Phone Number: " + body.phone;
}
else {
alldoc = "No records found";
}
res.send(alldoc);
});
});
app.post('/delete_contact', function(req, res) {
db.get(req.body.phone, {revs_info : true}, function(err, body) {
if(!err) {
db.destroy(req.body.phone, body._rev, function(err, body) {
if(err) {
res.send("error deleting contact");
}
});
res.send("Contacts deleted successfullly");
}
});
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port: ' + app.get('port'));
});
index.js
exports.index = function(req,res) {
res.render('index', {title: 'express'});
};
createdb.js
exports.create = function(req, res) {
nano.db.create(req.body.dbname, function() {
if(err) {
res.send("Error creating the Database");
return;
}
res.send("database created successfully");
});
};
index.js and createdb.js both are in routes folder
index.jade
extend layout
block content
h1 Add new Contact
form(method="POST", action = '/new_contact')
p name:
input#title(type = "text", name = "name")
p Phone No.:
input#title(type = "text", name = "phone")
p: button(type = "submit") Add new Contact
h1 Add new Database
form(method = "POST", action= "/createdb")
p Database name:
input#title(type = "text", name = "dbname")
p: button(type="submit") Add new Database
h1 enter Phone number to delete new_contact
form(method = "POST", action= "/delete_contact")
p Phone No.:
input#title(type = "text", name = "phone")
p: button(type="submit") Delete Contact
h1 View Specific contact
form(method = "POST", action= "/view_contact")
p Phone No.:
input#title(type = "text", name = "phone")
p: button(type="submit") Search Contact
layout.jade
doctype html
html
head
title = title
//- link(rel='stylesheet', href='/stylesheet/style.css')
body
block content
layout.jade and index.jade are present in views folder
package.json
{
"name": "sample",
"version": "1.0.0",
"description": "just a sample.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"errorhandler": "^1.5.1",
"express": "^4.17.1",
"express-session": "^1.17.1",
"jade": "^1.11.0",
"json": "^10.0.0",
"logger": "0.0.1",
"method-override": "^3.0.0",
"nano": "^9.0.3",
"pug": "^3.0.2",
"serve-favicon": "^2.5.0",
"url": "^0.11.0"
}
}
Just briefly skimming over the code, it looks like you're not passing any authentication details to nano:
var nano = require('nano')('http://localhost:5984');
var db = nano.use('address');
/* ... */
app.post('/createdb', function(req, res) {
nano.db.create(req.body.dbname, function(err){
This might have worked in old versions of CouchDB running in admin party mode, which is not supported anymore from CouchDB 3.0 onwards.
When installing CouchDB locally, you'll need to setup a admin user and password before getting started.
When using nano, you need to provide the credentials like:
var nano = require('nano')('http://admin:password#localhost:5984')
So im trying to deploy a simple twitter like app to HEROKU or MongoDB and i'm currently nailing either. 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. Since I have two separate folders for each implementation i'm going to post subsequently.
MONGODB
Index.js (This is the server side node code)
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
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
{
"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
{
"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. 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
Here i'm pretty sure im doing something wrong on the index.js or client.js or both. 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. 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
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
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"
}
}
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. Cheers to any isolated folks!
Change index.js file
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
So im using express as a simple backend for my client application. When trying to make a request to the endpoint GET /urls below it keep getting this message.
Access to fetch at 'http://localhost:5000/urls' from origin 'http://localhost:3000' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
My express server looks like so
require("dotenv/config");
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const ShortUrl = require("./modules/shortUrl");
var whitelist = ['http://localhost:3000']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
mongoose
.connect(process.env.MONGO_DB_CONNECTIONSTRING, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("\nConnected to Mongo Database\n"));
app.get("/urls", cors(corsOptions), async (req, res) => {
const shortUrls = await ShortUrl.find();
res.send({ serverBaseUrl: process.env.SERVER_BASE_URL, shortUrls });
});
app.post("/url", cors(corsOptions), async (req, res) => {
console.log(req.body);
await ShortUrl.create({ full: req.body.fullUrl });
res.send();
});
app.get("/:shortUrl", cors(corsOptions), async (req, res) => {
const url = await ShortUrl.findOne({ short: req.params.shortUrl });
if (url === null) return res.sendStatus(404);
url.clicks++;
await url.save();
res.redirect(url.full);
});
app.listen(process.env.PORT || 5000);
In my web application I'm using a fetcher, I quickly typed up so it could be something in there which isnt quite right.
const createFetchOptions = (method, body = undefined) => {
const options = {
method,
headers: {}
};
if (body && body instanceof FormData) {
options.body = body;
} else if (body) {
options.headers["Content-type"] = "application/json";
options.body = JSON.stringify(body);
}
return options;
};
const Fetcher = {
get: async url => {
const res = await fetch(url, createFetchOptions("GET"));
return res;
},
post: async (url, body) => {
const res = await fetch(url, createFetchOptions("POST", body));
return res;
}
};
export default Fetcher;
This is a copy of my package,json incase its todo with a version issue
{
"name": "url_shortner",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"ejs": "^3.0.1",
"express": "^4.17.1",
"mongoose": "^5.9.4",
"shortid": "^2.2.15"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
Any help would be appreciated,
Chris.
When you use app.use(cors()); it becomes middleware for all requests. Therefore, you don't need to manually add it to your routes. If you want to whitelist one particular domain for all routes, then you can utilize the origin option (I set it as a process string variable to be more flexible for development and production environments):
const { CLIENT } = process.env;
app.use(
cors({
origin: CLIENT, // "http://localhost:3000" for dev and "https://example.com" for production
})
);