Post Request not Calle - javascript

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}!`))

Related

Svelte don't load components with node.js

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!

res.send Not sending any data - Express.js

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.

Socket.io Connection Event Not Triggering

I am new to using socket.io and I have tried to set up a basic functionality according to the docs and youtube tutorials. My program is supposed to console log "New socket connection" when I navigate to the index page. However, the event is not triggering. Am I missing something? Thanks!
My app.js file
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const io = socket(server);
app.set("view engine", "ejs");
// Set static folder
app.use("/public", express.static("public"));
app.get('/', (req, res) => {
console.log("Reached index page")
res.render("index")
});
app.get('/room', (req, res) => {
console.log("Reach room page")
res.render("room")
});
// Run when a client connects
io.on("connection", (socket) => {
console.log("New socket connection")
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running. Navigate to localhost:${PORT}`));
My index.ejs file
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<link rel="icon" href="../public/">
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../public/index/css/index.css" />
</head>
<body>
click here
<script>
var socket = io(); // this line is supposed to be sufficient to trigger
// the socket connection
</script>
<script src="../routes/index.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
The error resulted from my naming my variable 'socket' when importing the socket.io dependency. The socket param in the line 'io.on("connection", (socket)' is supposed to reference another socket variable not the one that I created. Common practice is to name the dependency variable 'socketio' instead of 'socket'

How to get into html source code by rest request

I want to render some value of another website by fetching the HTML source data by REST request, console the value inside the span tag to my console log and render it to my HTML.
I can't managed to this by my current code, he receives the data before the DOM is ready and the specific san tag i need still not there.
My current code -
async function uiTagChecking() {
let url ='http://production.com:8000/loginPage#';
fetch(url)
.then(await sleep(6000))
.then(response => response.text())
.then(pageSource => console.log(pageSource));
}
The current source code I've fetched (this is before the DOM is ready and the needed span tag doesn't there yet)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>loading...</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon"
type="image/png"
href="images/favicon.png?v=9">
<!--<link href="assets/vendors/keylines/map/leaflet.css" rel="stylesheet">-->
<link href="XXXX" rel="stylesheet"></head>
<body>
<div id="app"></div>
<script src="assets/vendors/jquery.min.js"></script>
<script type="text/javascript" src="XXXX/index-c08574aac712ae81e016.js"></script></body>
</html>
The span tag i want to print and render -
<span class="version-for-qa">2.1.1</span>
But it appears only after the redirect is ended and the DOM is ready.
Technical info:
Node JS
JavaScript
HTML + CSS
My server file (express):
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var fs = require('fs');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
app.use(cors());
app.set(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});

Using the Express.js app.post request is not working

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.

Categories