How to read a file in node js? - node.js

When i want to read a file in node js it won't display the file in the browser when I execute.
and in the terminal says no such file or directory while I use the exact file path anyone can answer this why?
Here is the code:
const express = require('express');
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const CORS = require('cors');
let port = 3000;
app.use(CORS());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static('Docs'));
app.get('/', (req, res) => {
res.json({name: 'waris', favFood: 'Pizza'})
fs.readFile('./docs/index.html', (err, data) => {
if(err){
console.log(err)
}else{
res.send(data);
}
})
})
app.listen(port, () => {
console.log(`Running on port ${port}`);
})

Related

Heroku Cannot GET/

I deployed my project with Heroku and everything works correctly but when I refresh the page I received the error "Cannot GET /home". Is there anyone can help me? https://fresh-bio.herokuapp.com/
server.js:
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static("client/build"));
app.get("/", function (req, res) {
res.sendFile("client/build/index.html");
});
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static(__dirname + "/client/build/"));
app.get(/.*/, (req, res) => {
res.sendFile(__dirname + "/client/build/index.html");
});
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);

Error - Can not see text in visual code when doing a request

I have a simple basic node.js entry file by the name of index.js and the below code for this file is as following:
const express = require("express");
const expressApp = require("./express-app/test.js");
const { PORT } = require("./config");
const { databaseConnection } = require("./database");
const StartServer = async () => {
const app = express();
//database connection
await databaseConnection();
expressApp(app);
app
.listen(PORT, () => console.log(`Customer is listening on port ${PORT}`))
.on("error", (err) => {
console.log(err);
process.exit();
});
};
StartServer();
and also have a file by the name of test.js with the following code as below:
const express = require("express");
const cors = require("cors");
module.exports = (app) => {
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: true, limit: "1mb" }));
app.use(cors);
app.use(express.static(__dirname + "/public"));
// Listen to Events //
app.use("/app-events", (req, res, next) => {
console.log("Had reached");
});
};
When I do a request with url http://localhost:portnumber/app-events, I can not see "Had reached" in the console.
I'm wondering what am I doing wrong??
I think it should be app.get(...) instead of app.use(..)

nodejs express req.body undefined

I write this code and req.body is undefined
I want to get post value in my program
can you help me, please?
const express = require('express')
const app = express()
const port = 3000
const crypto = require('crypto');
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
You body-parser npm package
$ npm i body-parser
var express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
const crypto = require('crypto');
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Instead of using body parser, Express already providing support for that,
import express from "express";
const app = express();
app.use(express.json());
app.use(express.urlencoded());
This should be given before the Api route

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨‍🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

POST route indicating 404 error (EXPRESS)

Getting a 404 error on my POST route, here is what I have done in my auth.js (routes) file:
const express = require('express');
const router = express.Router();
const connection = require('../../helpers/db.js');
const bodyParser = require("body-parser");
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({
extended: true
}));
//create a new user
router.post('/signup', function (req, res) {
const insert = `INSERT INTO users ( email, password, name, lastname) values ('${req.body.email}', '${req.body.password}','${req.body.name}', '${req.body.lastname}' )`
connection.query(insert, function (err, result) {
if(err) {
console.log('mysql error', error);
res.status(500);
res.send(error);
} else {
console.log('a new user was added!');
res.send('Congrats, new user!');
}
})
});
module.exports = router;
Here is my app.js file:
const http = require("http");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const app = express();
const authRouter = require("./routes/auth/auth");
// Configuring the app
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.use("/signup", authRouter);
//starting node server
const server = app.listen(process.env.PORT || 3001, function(err) {
if(err) throw err;
console.log("Listening on port " + server.address().port);
});
If I change my route into a GET, it works fine, but as soon as I do a POST route it would keep telling me on postman there is a 404 error, been trying many things but im now stuck! Im a beginner here :)
I think you added a prefix to your route so the route is /signup/signup
Try to change this
app.use("/signup", authRouter);
To this
app.use(authRouter);

Resources