So I am working on this calculator app using Express.js and when I use the res.send Method I am not receiving any kind of response now.
I expect my webpage to send me the sum as in the calculator.js file.
I am using nodemon as well.
This is HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="POST">
<input name='num1' placeholder='num1' type='text'>
<input name='num2' placeholder='num2' type='text'>
<button
type="submit" name="submit">Calculate</button></form>
<h1 class='answer'></h1>
</body>
</html>
This is calculator.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const {
json,
urlencoded
} = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html")
});;
app.post("/", function (req, res) {
console.log(req.body);
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var sum = num1 + num2;
res.send(sum);
});
app.listen(port, () => console.log(`Example app listening on port port!`))
you can't use res.send() to send number, it will be sent as a http status code. You can simply convert calculated sum to string and then send it:
res.send(sum.toString())
res.send has been deprecated in the latest version of Express (4.17.1).
Using res.sendStatus instead solved my problem.
Related
I'm trying to load a markdown file as a static file which should afterwards be rendered via a html file. My question now is how I am to apply CSS Styling. Here is my code for the index.js:
const express = require('express');
const bodyparser = require('body-parser');
const showdown = require('showdown');
const marked = require('marked');
const app = express()
app.use(express.static(__dirname + '/'));
app.use(bodyparser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.use(express.static('public'));
app.get('/article', (req,res)=> {
var markdown = require("markdown-js");
var fs = require("fs");
var path = __dirname+'articles/article.md'
app.use(express.static("public"));
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
console.log(err);
}
//res.send(marked("" + data));
//console.log(result);
res.render('index.html');
});
});
// listen to port
const PORT= 3000;
app.listen(process.env.PORT || 3000, function(){
console.log('server is running on port 3000');
})
The code for my current html file looks the following such that index.html:
<!DOCTYPE html>
<html lang="en">
<script src="style.css"></script>
<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>Document</title>
</head>
<body>
<% result %>
</body>
</html>
In order to use variables you have to use ejs you can read about it here https://ejs.co/
then you can do something like this:
First change the name to index.ejs
Then you have to pass the data
res.render("index", { result: data })
I want to build an application with Node.js and Svelte, but when I try to import a component it wasn't load.
Server side code:
const app = require("express")();
const http = require("http").Server(app);
const port = process.env.PORT || 8080;
const io = require("socket.io")(http);
const fs = require('fs')
const express = require('express')
app.get('/', (req, res) => {
res.write(fs.readFileSync('./pages/homepage.svelte', 'utf-8'));
res.end();
});
io.sockets.on('connection', function (socket) {
console.log('Utente connesso!')
});
http.listen(port, function() {
console.log("Listening on *:" + port);
});
Homepage.svelte:
<script>
import Component from './components/Component.svelte'
</script>
<!DOCTYPE html>
<html lang="it">
<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>SocialTree</title>
</head>
<body>
<Component />
</body>
</html>
Component.svelte code:
<div>
<h1>Test</h1>
</div>
Thanks in advice and sorry for bad english!
SI have an express server running. In the app.post ('/ login'), I have a data object that has a name and a password which i obtained from a form. I would like to forward this data to another EJS page.
app.js --> server
const express = require('express');
const app = express();
const port = 3000 || process.env.PORT;
app.use(express.json());
//Set the views + engine
app.set('views', './views');
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index');
});
app.get('/about', (req, res) => {
res.render('about');
});
app.post('/login', (req, res) => {
const data = req.body;
res.render('about', {data: data}); //i want to send this data to the about page and priew it on the screen
});
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
})
about.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Data</h1>
<p><%= data %></p> <!--Preview to entred data from the user here-->
</body>
</html>
So I'm learning node.js and I've hit a wall. My post request is not getting triggered.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
Setting up server
var server = http.createServer(function(req,res){
console.log('request was made: ' + req.url);
if (req.url === '/home' || req.url === '/'){
fs.readFile("./index.html",null,function(error,data){
if (error) throw error;
res.write(data);
res.end();
});
} else {
console.log("404");
}
})
The post-request that refuse to work
app.post('/test', function(req,res){
console.log("post req came thru");
})
Listening...
server.listen(8080)
HTML
<!DOCTYPE html>
<html>
<head>
<title>CRUD App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="/test" method="POST" >
<input type="text" name="test"></input>
<button>Submit</button>
</form>
</body>
</html>
You need to pass the Express app as a parameter to the http.createServer function otherwise it won't be handling any of your requests. Either that, or use the actual app.listen method:
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I am having an issue with the Express.js library.
I have been trying to set up a basic post request with the route.
I have installed and using body-parser for the post data.
If I specifically add app.post it does not work but if I use GET or app.all it works just fine with my post data.
Could some one take a look at my code and see what i could be doing wrong? Also just for a further clarification i will be splitting all this up later on i just have the data base connection and every thing else in one file to test things.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
console.log(silence);
});
res.render('def',{
firstnames:getuser_Information
});
});
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form class="navbar-form navbar-left" role="search" method="post">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
So i was not routing the correct information and figured out the diffrences of when using app.all. here is the code that i have now.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.get('/',function(req, res) {
res.render('def',{
firstnames:""
});
});
app.post('/run',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
process.on('uncaughtException', function (err) {
console.log("\n\r *Uncaught Exception event* \n\r")
console.log(err);
});
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form action="/run" class="navbar-form navbar-left" role="search" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
Node.js is asynchronous.