API REST node & Express.js deploy in Render - node.js

I am deploying the server part of a project, built in node and express and it says that the server is live but it doesn't work. In console I get the errors:
" Failed to load resource: the server responded with a status of 404 ()",
" Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Lato:300,400,700,900' because it violates the following Content Security Policy directive: "default-src 'none'". Note that "style-src-elem" was not explicitly set, so 'default-src' is used as a fallback.".
I don't understand why it gives me that error, since there is no css or html file...
here is my entry js file:
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const xss = require('xss-clean')
const mongoSanitize = require('express-mongo-sanitize')
const { handleError, convertToApiError } = require('./middleware/apiError')
const routes = require('./routes')
const passport = require('passport')
const { jwtStrategy } = require('./middleware/passport')
require('dotenv').config()
const mongoUri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#${process.env.DB_HOST}? retryWrites=true&w=majority`
mongoose
.set("strictQuery", false)
.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((x) => {
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`
)
})
.catch((err) => {
console.error("Error connecting to Mongo: ", err)
})
//// body parse
app.use(express.json())
//// sanitize
app.use(xss())
app.use(mongoSanitize())
//// passport
app.use(passport.initialize())
passport.use('jwt', jwtStrategy)
//// routes
app.use('/api', routes)
//// handle errors
app.use(convertToApiError)
app.use((err, req, res, next) => {
handleError(err, res)
})
const port = process.env.PORT || 5005
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
I don't even know what I could do...

Related

MERN App - Error when hosting my app on heroku

different response result when I use localhost url or the heroku url
As you can see in the picture, in blue we succesfully have the result response. But not when hosted in heroku (green on picture).
Here is the response from api when I try to fetch:
response
But those params are set in .env file (backend).
Can someone help me with this ? The cors is configured on the backend, so I don't know what I can do more...
server.js:
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require("dotenv");
const colors = require("colors");
const dbConnect = require("./database/dbConnect");
dotenv.config();
// *** ROUTES IMPORT ***
const usersRoutes = require("./routes/users-routes");
const ovhRoutes = require("./routes/ovh-routes");
const renewDomainsRoutes = require("./routes/renew-domain-routes");
const meRoutes = require("./routes/me-routes");
const internetBsRoutes = require("./routes/internetbs-routes");
const domainsRoutes = require("./routes/domains-routes");
const orderRoutes = require("./routes/order-routes");
// execute database connection
dbConnect();
const app = express();
app.use(bodyParser.json());
app.use(cors());
/**
* ROUTES
*/
app.use("/api/users", usersRoutes); // => /api/users/...
app.use("/api/ovh", ovhRoutes); // => /api/ovh/...
app.use("/api/renew", renewDomainsRoutes);
app.use("/api/me", meRoutes);
app.use("/api/internetbs", internetBsRoutes);
app.use("/api/domains", domainsRoutes);
app.use("/api/order", orderRoutes);
app.use((req, res, next) => {
throw new HttpError("Could not find this route.", 404);
});
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500);
res.json({ message: error.message || "An unknown error occurred!" });
});
/**
* DEPLOYMENT
*/
if (process.env.NODE_ENV === "production") {
// Step 1:
app.use(express.static(path.resolve(__dirname, "./client/build")));
// Step 2:
app.get("*", function (request, response) {
response.sendFile(path.resolve(__dirname, "./client/build", "index.html"));
});
}
app.listen(
process.env.PORT || 5000,
console.log(`Server is running on port ${process.env.PORT}`.blue.bold)
);
The data are fetched from internet.bs API.
Thanks all!

Axios- Node JS cookie parser is returning a empty object

I am working on my Project. When I was using Axios I ran into a few problems that I do not get.
Here I saw a similar question that represents my situation:
Node JS cookie parser not working
Here is my React Code with Axios installed and Imported:
useEffect(() => {
axios.get('http://localhost:5000/get-cookie')
.then(response => {
console.log(response.data);
})
}, [])
And my app.js code
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const Grid = require("gridfs-stream");
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || 5000;
require('dotenv').config()
//middleware
app.use(cors());
app.use(express.json());
// connecting to database
let gfs;
const uri = process.env.DB
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const conn = mongoose.connection;
conn.once("open", function () {
console.log("MongoDB database connection established successfully");
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("photos");
});
// cookie routes
app.use(cookieParser());
app.get('/set-cookie/:id', (req, res) => {
res.cookie("User_ID", req.params.id, {maxAge: 1000 * 60 * 60 * 24 * 31, httpOnly: true})
res.json("You setted the cookies")
});
app.get('/get-cookie', (req, res) => {
var cookies = req.cookies
res.json(cookies)
});
// custom routes
const notes_router = require('./routes/notes')
const avatar_router = require('./routes/avatar');
const user_router = require('./routes/user');
app.use(avatar_router);
app.use(user_router);
app.use(notes_router);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
module.exports = gfs
I tested these on postman and they worked.
So I need help
Axios by default don't send cookies but you can pass the option withCredentials as true and it should work
useEffect(() => {
axios.get('http://localhost:5000/get-cookie',{withCredentials: true})
.then(response => {
console.log(response.data);
})
}, [])
EDIT: You will have to set the CORS policy on you Express app as well for this to work you can try the below middleware (assuming your react app is running on localhost:3000, you can change it match with you):
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
Or you can use CORS npm package as well.

Can't retrieve information from mongodb when deploying on heroku

The problem is as the title suggests. When I run my app locally, I'm able to retrieve information from MongoDB but on Heroku, undefined is returned. Should I connect to MongoDB in another way because if I hardcode some text everything works just fine. Here are my scripts:
function to get data
const MongoClient = require("mongodb").MongoClient;
const dbConnectionUrl = "mongodb+srv://xxxxxxx#cluster0.ro4dz.mongodb.net/data?retryWrites=true&w=majority";
const saySomething = (req, res, next) => {
// res.status(200).json({
// body: 'Hello from the server!'
// });
login()
.then(val=>res.send(val))
};
async function login(){
const client = new MongoClient(dbConnectionUrl)
try{
await client.connect();
const database = client.db("data");
const movies = database.collection("movies");
const query = { name: "toke" };
const movie = await movies.findOne(query);
return movie
}catch(err){
console.log(err)
}
}
module.exports.saySomething = saySomething;
router
const express = require('express');
const router = express.Router();
const controllers = require('./../controllers/controllers');
router.get('/say-something', controllers.saySomething);
module.exports = router;
server
// Import dependencies
const express = require('express');
const cors = require('cors');
const path = require('path');
// Create a new express application named 'app'
const app = express();
// Set our backend port to be either an environment variable or port 5000
const port = process.env.PORT || 5000;
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the CORs middleware
// Require Route
app.use(cors());
const api = require('./routes/routes');
// Configure app to use route
app.use('/api', api);
// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
};
// Catch any bad requests
app.get('*', (req, res) => {
res.status(200).json({
msg: 'Catch All'
});
});
// Configure our server to listen on the port defiend by our port variable
app.listen(port, () => console.log(`BACK_END_SERVICE_PORT: ${port}`));
front
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios'
function App(){
useEffect(()=>{
get()
})
const[text, settext] = useState('')
async function get(){
let request = await axios.get('/api/say-something')
console.log(request.data.name)
settext(request.data.name)
}
return(
<div>{text}</div>
)
}
export default App;
I solved the issue! The first thing I did was that I added MongoDB connection URI as an environmental variable in my app via Heroku. Secondly, I added an option in MongoDB so that the cluster can be accessed from any computer. By default, the access is set to the local computer so I added another IP, namely 0.0.0.0/0 to my cluster, and now everything works just fine.

Question about Authentication on MONGODB+Node

I have a tutorial how to create it,
im on stage he tell me to do something like this "user-registration $export PrivateKey=SecureAF"
what is this mean? what should i do ?
The ERROR at "npm start" is : "FATAL ERROR: PrivateKey is not defined."
index.js :
const config = require('config');
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
const express = require('express');
const app = express();
if (!config.get('PrivateKey')) {
console.error('FATAL ERROR: PrivateKey is not defined.');
process.exit(1);
}
mongoose.connect('mongodb+srv://test:test#cluster0-7n3bu.mongodb.net/test?retryWrites=true&w=majority',
{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
app.use(express.json());
app.use('/api/users', users);
app.use('/api/auth', auth);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Why you are having the error:
The check below in index.js is what leads to the error:
if (!config.get('PrivateKey')) {
console.error('FATAL ERROR: PrivateKey is not defined.');
process.exit(1);
}
config.get('PrivateKey') is supposed to get the value of PrivateKey in your config, however, it seems that value is not present, consequently, the app exits with the error log.
The fix:
I'm guessing you have a config folder in the root of your application, yes? If yes, check your ./config/default.json or ./config/development.json and confirm that there is a PrivateKey config property with a valid value.

API Route for retrieving a MongoDB collection

I'm trying to retrieve data from my mongo database. The problem occurs when I try to do the get route in my API. The error I get is: SchemeName.collection is not a function.
Here is my API in routes/api/tejidos
const express = require("express");
const router = express.Router();
const Equipo = require("../../../models/Equipo");
router.post("/crear", (req, res) => {
// Form validation
const newEquipo = new Equipo({
nombre: req.body.nombre,
marca: req.body.marca,
modelo: req.body.modelo,
serial: req.body.serial,
proveedor: req.body.proveedor,
estado: req.body.estado,
zona: req.body.zona,
fechaCompra: req.body.fechaCompra,
tiempoGarantia: req.body.tiempoGarantia,
guiaUsoRapido:req.body.guiaUsoRapido
});
//if (err) throw err
newEquipo
.save()
.then(equipo=>res.json(equipo))
.catch(err => console.log(err));
});
router.get('/leer', function(req, res) {
const equipos = Equipo.collection("equipos")
res.json({
equipos: equipos
});
});
module.exports = router;
And this is my server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const equipos = require("./routes/api/tejidos/equipos");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/tejidos/equipos", equipos);
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running... ${port} !`));
I need to retrieve data in my collection (the ones I created with the post method) from the database when I use the GET method in Postman at http://localhost:5000/api/tejidos/equipos/leer
Also, I will appreciate any documentation that you recommend.
Simply use find method:
router.get('/leer', async (req, res) => {
const equipos = await Equipo.find();
res.json({ equipos });
});
And here is the helpful documentation for making queries with mongoose

Resources