Getting Cannot GET / in NodeJS Express project - javascript

I've tried numerous methods to solve this from app.use(express.static(__dirname + "public")) to res.render and it works in my terminal but not in my local host. Where am I going wrong?
Here's my JS file:
const express = require('express');
const bodyParser = require('body-parser');
var fs = require ('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
//app.use(express.static(__dirname + '/public'));
//app.get('/index.html', (request, response) => response.sendFile( __dirname, "/index.html"));
app.post('/userinfo', (request, response) => {
const postBody = request.body;
console.log(postBody);
response.send(postBody);
});
app.listen(3002, () => console.info('Application running on port 3002'));
And here's my HTML file:
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Express - Node.js POST data example</title>
</head>
<body>
<form action="/userinfo" method="POST">
Some data: <input type="text" name="data" id="data">
<button type="submit">Send</button>
</form>
</body>
</html>

There is no response for base url or / route is defined. You have defined only two routes and I assume /index for your index page. So, the page will be render at localhost:3002/index . You have to define another response for / or base url like,
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
Hopefully, your problem will be solved.

Related

Logging upon receiving POST request in Express

I have recently started picking up Node.js with the Express framework. I created a simple server and attached an HTML file with a form consisted of a single button of type submit which was supposed to send a post request to the server. It doesn't give me any errors but when I try to log a message to the console upon pressing the submit button, nothing happens. I am pretty sure it has something to do with the HTML form syntax but I can never be too sure. Here is the HTML:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form class="test" action="http://localhost:8000/example" method="post">
<input type="submit" name="but" value="Press me">
</form>
</body>
</html>
Here is the Express code:
const http = require("http");
const app = require("express")();
const path = require('path');
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/example", (req, res) => {
console.log("pressed");
});
app.listen(8000, ()=>{
console.log("Running at 8000");
});
It's occurs because app.use () is treated as middleware for your application. To work properly you should use app.get (). Here is more detailed explanation. Other alternative is provide your html as an static content, you can see more about here.
To work properly you should change your code to this:
app.get("/", (req, res) => {
  res.sendFile(__ dirname + "/index.html");
});
You can also modify your HTML to this:
<form class="test" action="/example" method="post">
Because is in the same host. You just use complete url when performing action to other host.
Change this...
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
to this...
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

using socket.io with express router

I am fairly new to node.js, I am trying to build a webchat and so far I have a server.js file and a router.js file that should have all my routes inside. I am not using express-generator. I would like to use socket.io but on my current setup it doesn't work.
Here is what I have
server.js
const path = require('path');
const express = require('express');
const layout = require('express-layout');
const app = express();
const routes = require('./router');
const bodyParser = require('body-parser');
var server = require('http').createServer(app);
var io=require('socket.io')(server);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const middleware = [
layout(),
express.static(path.join(__dirname, 'public')),
bodyParser.urlencoded(),
];
app.use(middleware);
app.use('/', routes);
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
io.on('connection',function (socket) {
console.log('yo');
});
server.listen(3000, () => {
console.log(`App running at http://localhost:3000`);
});
router.js
const express = require('express');
const router = express.Router();
const {check, validationResult}=require('express-validator');
const { matchedData } = require('express-validator/filter')
const app = express();
router.get('/', (req, res) => {
res.render('index', {
data: {},
errors: {}
})
});
router.post('/enter', [
check('username')
.isLength({min: 1})
.withMessage('Username is required') //implement personalized check
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('index', {
data: req.body,
errors: errors.mapped()
})
}
const data = matchedData(req)
});
module.exports = router;
It should log "yo" on the console but it doesn't. I already tried to move the socket.io setup part to router.js, it doesn't give any errors but it does not log anything. Also if I set up correctly socket.io on my server.js, how do I pass it to router.js?
EDIT
there is the index.ejs file that has some client code that initializes the connection with socket.io
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Global.io</title>
<link type="text/css" rel="stylesheet" href="/index.css">
<script>
var socket = io();
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
console.log('yo client');
});
</script>
<!-- <script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/scripts/client.js" defer></script> -->
</head>
<body>
<h1>Start debating about the change</h1>
<div id="wrapper">
<form id="formElem" method="post" action="/enter" novalidate>
<% if (errors.username) { %>
<div class="error"><%= errors.username.msg %></div>
<% } %>
<input id='name' type="text" name="user" placeholder="User name" class=" <%= errors.username ? 'form-field-invalid' : ''%>">
<select name="room" id="room">
</select>
<button type="submit" id="submit-b">Submit</button>
</form>
</div>
</body>
</html>
Now it gives an error saying io is undefined.
You need this:
<script src="/socket.io/socket.io.js"></script>
Before the script that tries to use socket.io in your web page. That script loads the socket.io library and defines the io symbol so you can then use it after the library has been loaded.

Displaying Contents of Mongodb Database on webpage

I am trying to display the contents of my database on a webpage.
The way I want to do it is by displaying the content in the database by descending order. I have made the connection to MongoDB and am able to see my data in the terminal stored correctly. I just can't seem to figure out how to display that stored data now.
Thanks!
Server.js file.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true })
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var nameSchema = new mongoose.Schema({
Alert: String
});
var User = mongoose.model("User", nameSchema);
app.listen(3000, function() {
console.log('listening on 3000')
})
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.get('/alertview', (req, res) => {
res.sendFile(__dirname + '/alertview.html')
})
app.post('/', urlencodedParser, function (req, res) {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
User.find({},function(err,docs){
console.log(docs);
})
Html file I want to display the alerts on.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/alertpageStyle.css" media="screen" />
<meta charset="UTF-8">
<title>View Alerts</title>
</head>
<body>
<div class="header">
<h1>Current Alerts</h1>
</div>
</body>
</html>
Simple example using the EJS templating, essentially you pass your object to the template at the time of rendering. You can also iterate over data. Same approach can be used for Handlebars or Mustache packages.
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', index);
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>

Can't load static files in index.html

I'm trying setup simple app with node, express and angular2. The problem is that, when I run localhost, open it in browser, I get errors: "Uncaught SyntaxError: Unexpected token <". I think it happens because of incorrect path or wrong code in my node/express files.
For example, when I'm trying open library file in source, I always get index.html code :
Here is the folder structure:
Below I'll show full code
index.js
'use strict'
// require dependencies
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
// require our custom dependencies
let router = require('./router');
let app = express();
const PORT = process.env.PORT || 4000;
// get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//share folder with static content
app.use(express.static(__dirname + '../frontend/build'));
app.use('/', router);
app.listen(PORT, function() {
console.log('Example app listening on port', PORT);
});
router.js
let express = require('express');
let router = express.Router();
let path = require('path');
let User = require('./models/user');
router.use(function(req, res, next) {
console.log('request to', req.path);
next();
});
router.route('/users')
.get(function(req, res) {
User.find(function(err, users) {
if (err) {
res.send(err);
}
res.json(users);
});
});
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
})
module.exports = router;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Angular 2 App!</title>
<base href="/">
<!-- load the dependencies -->
<script src="./assets/libs/core-js/client/shim.min.js"></script>
<script src="./assets/libs/zone.js/dist/zone.js"></script>
<script src="./assets/libs/reflect-metadata/Reflect.js"></script>
<script src="./assets/libs/systemjs/dist/system.src.js"></script>
<script src="./systemjs.config.js"></script>
<script>
System.import('app').catch(function(err) {
console.error(err);
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Thanks!
Update
I changed in router.js from this
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
to this
router.get('/', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
and now I have 404 error, files not found

Why can't I upload a file?

I'm trying to upload a photo using Node.js. But when I upload, it shows this error:
Cannnot read property file of undefined
at C:\new\file.js:13:26
Looks like I'm doing something wrong with req.files.file.name which I don't understand. What can be the issue?
Here's the code:
file.js
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: '/files/'}).single('file'));
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + '/' + '/index.html')
});
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + '/' + req.files.file.name;
fs.readFile(req.files.file.name, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log("Error reading");
} else {
response = {
message: 'file uploaded successfully',
filename: req.files.file.name
};
}
console.log(response);
res.end(JSON.stringify(response));
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("The server is running at http://%s:%s ", host, port);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
</form>
</body>
</html>
Here's what I do, which works fine:
var uploadPath = 'public/uploads/';
var upload = multer({dest: uploadPath});
router.post('/image', upload.single('thePhoto'), function (req, res) {
var uploadedFile = uploadPath + req.file.filename;
The problem can be caused because you have already added multer in app.use() which parses all the data before the control goes to post method. So I think you should either use fs or multer but not both.

Categories

Resources