Global variable doesn't work on node.js server - javascript

I have simple javascript code and I don't understand why each time globalString is zero. Even after I call high. It should be global variable which will be same between method calls.
const express = require('express');
const { exec } = require('child_process');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var test_out = "";
var globalString = 0;
app.post('/high', (req, res) => {
globalString = 1;
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.post('/low', (req, res) => {
globalString = 0;
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.post('/state', (req, res) => {
globalString = 0;
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.listen(4000, () => console.log('Server is up.'));

As suggested in above comment " you are setting globalString 0 every time api get called"
const express = require('express');
const { exec } = require('child_process');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var test_out = "";
var globalString = 0;
app.post('/high', (req, res) => {
globalString = 1;
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.post('/low', (req, res) => {
//globalString = 0; you are setting globalString 0 every time this api get called
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.post('/state', (req, res) => {
//globalString = 0; you are setting globalString 0 every time this api get called
return res.status(200).json({ result: 'ok' , message: globalString.toString() });
});
app.listen(4000, () => console.log('Server is up.'));

Related

how do I redirect to another page?

I want to make a redirect to another page if the data is inserted, but for some reason it does not work. please tell me how you can do this? there were different ways, but even argulatorjs didn't help.
let express = require("express");
let app = express();
let port = 3000;
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
let angular = require('angular');
let mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/test");
let nameSchema = new mongoose.Schema({
name: String,
login: String,
password: String,
authorization: Boolean
});
let User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
let myData = new User(req.body);
myData.save()
.then(item => {
res.send("Вы успешно зарегистрировались, перенаправление...");
$window.location.href = '/CA.html';
})
.catch(err => {
res.status(400).send("Что-то пошло не так");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
You can use it in your end-point like this;
app.get('/stackoverflow', (req, res) => {
// Redirect goes to stackoverflow
res.redirect('https://stackoverflow.com/');
})

Cannot read fetch data on express server

On the client side, I have an application based on threejs an d javascript. I want to send data to the server written in express using fetch. Unfortunately, the server does not receive the data and the browser also gives an error:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Application:
this.username = prompt("Username:");
const body = JSON.stringify({ username: this.username });
fetch("http://localhost:3000/addUser", { method: "POST", body })
.then((response) => response.json())
.then(
(data) => (
console.log(data), (this.aktualny_album_piosenki = data.files)
)
);
Server:
var express = require("express")
var app = express()
const PORT = 3000;
var path = require("path");
app.use(express.static('dist'));
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.post("/addUser", function (req, res) {
console.log(req.body)
})
I might be wrong but maybe try... (very bottom of your main server file)
app.listen((PORT) => {
console.log(`app is listening on port ${PORT}`);
})
is required maybe? I have this chunk of code in every project of my own so maybe that could fix the server not recognizing the api request
express documentation on app listen
heres what I use typically... this is a boilerplate for every one of my projects
const express = require("express");
const app = express();
const connectDB = require("./config/db.js");
const router = express.Router();
const config = require("config");
// init middleware
const bodyParser = require('body-parser');
const cors = require("cors");
const mongoDB = require("./config/db.js");
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const xss = require('xss-clean');
const helmet = require("helmet");
const mongoSanitize = require('express-mongo-sanitize');
const rateLimit = require("express-rate-limit");
const PORT = process.env.PORT || 5000;
mongoDB();
app.options('*', cors());
app.use('*', cors());
app.use(cors());
const limitSize = (fn) => {
return (req, res, next) => {
if (req.path === '/upload/profile/pic/video') {
fn(req, res, next);
} else {
next();
}
}
}
const limiter = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000 * 1000, // remove the last 1000 for production
message: 'Too many requests' // message to send
});
app.use(xss());
app.use(helmet());
app.use(mongoSanitize());
app.use(limiter);
// app.use routes go here... e.g. app.use("/login", require("./routes/file.js");
app.get('*', function(req, res) {
res.sendFile(__dirname, './client/public/index.html')
})
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.get('/*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
if (process.env.NODE_ENV === "production") {
// Express will serve up production files
app.use(express.static("client/build"));
// serve up index.html file if it doenst recognize the route
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
}
})
app.get('/*', cors(), function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
};
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}!`);
});
client-side fetch request looks good to me its prob a server/express.JS thing but like i said i may be wrong but worth trying

'toString()' showing undefined

const express = require("express");
const app = express();
var fetchUrl = require("fetch").fetchUrl;
var wordsCounter = require("word-counting");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post("/game", (req, res) => {
const data= req.body;
console.log(data.website)
fetchUrl(`${data.website}`, (error, meta, body) =>{
let answer = wordsCounter(body.toString(), { isHtml: true }).wordsCount;
console.log(answer)
res.send({answer});
});
});
app.listen(6000, () => {
console.log("Server in action!");
});
I was trying to convert the HTML body to string so as to count the number of words but it's showing TypeError, Why is it so?

Multer not storing file to folder and is showing null in mongoDB

i am using nodejs with multer to create a Image file upload to my shopDB mongo DB
when i upload a image file and post the data from the form ... everything in the form gets saved in the DB but the imagename is showing null and the image is not getting stored in the file path
i am getting no error in the console while saving the form data
and the app is running fine except for the file upload
this is how the upload is inside the form
<div id="img">
<input type='file' name="uploadpostfile">
</div>
THIS IS MY APP.JS
const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require("path");
const Post = require('./models/postup');
const uploadPath = path.join("public", Post.postImgPath);
const bodyParser = require("body-parser");
const imageMimeTypes = ["images/jpeg", "images/png", "images/gif"]
const upload = multer({
dest: uploadPath,
fileFilter: (req, file, callback) => {
callback(null, imageMimeTypes.includes(file.mimetype) )
}
})
const request = require("request");
const ejs = require("ejs");
require('./models/postup')
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/shopDB");
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true}))
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
app.post("/npost", multer(upload).single("uploadpostfile"), (req, res) => {
let fileName = req.file != null ? req.file.filename : null
let post = new Post({
tag: req.body.taginput,
title: req.body.posttitle,
link: req.body.extlink,
text1: req.body.textsmall,
text2: req.body.textmedium,
text3: req.body.textlarge,
imgname: fileName
})
post.save((err, doc) => {
if (!err)
res.redirect('editor');
else {
console.log('Error' +err )
}
})
})
app.get('/', (req, res) => {
res.render('index');
});
app.get('/editor', (req, res) => {
res.render('editor');
});
app.listen(3000, function(){
console.log("Server on 3000");
})
You can try after saving a post, update the image.
const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require("path");
const Post = require('./models/postup');
const uploadPath = path.join("public", Post.postImgPath);
const bodyParser = require("body-parser");
const imageMimeTypes = ["images/jpeg", "images/png", "images/gif"]
const upload = multer({
dest: uploadPath,
fileFilter: (req, file, callback) => {
callback(null, imageMimeTypes.includes(file.mimetype) )
}
})
const request = require("request");
const ejs = require("ejs");
require('./models/postup')
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/shopDB");
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose', {useNewUrlParser: true}, { useUnifiedTopology: true}))
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
app.post("/npost", multer(upload).single("uploadpostfile"), (req, res) => {
let fileName = req.file != null ? req.file.filename : null
let post = new Post({
tag: req.body.taginput,
title: req.body.posttitle,
link: req.body.extlink,
text1: req.body.textsmall,
text2: req.body.textmedium,
text3: req.body.textlarge,
})
post.save((err, doc) => {
if (!err)
res.redirect('editor');
else {
imgname = fileName;
post.findOneAndUpdate({ _id: doc._id }, { $set: imgname }, {
upsert: true, new: true }).exec((error, post) => {
if(error) {
res.status(500).json({ message:'internal server error' });
} else {
res.status(200).json({message:'image upload sucessfully.})
console.log('Error' +err )
}
})
})
app.get('/', (req, res) => {
res.render('index');
});
app.get('/editor', (req, res) => {
res.render('editor');
});
app.listen(3000, function(){
console.log("Server on 3000");
})

Sending data on server by fetch

Can someone explain to me why after sending a request, server returns POST {} {}- I mean empty objects?
I don't know where this data is. Why did it dissapear?
I have no idea how to solve it...
index.js:
window.addEventListener("DOMContentLoaded", () => {
const form = document.querySelector("form");
form.addEventListener("submit", event => {
console.log("włącza sie");
event.preventDefault();
const name = document.getElementById("name").value;
const password = document.getElementById("password").value;
fetch("http:localhost:3000/register", {
method: "POST",
body: JSON.stringify({ name, password })
})
.then(res => {
console.log(res);
})
.catch(error => console.log(error));
});
});
//server.js:
const http = require("http");
const app = require("./app");
const port = 3000;
const server = http.createServer(app);
server.listen(port, () => {
console.log("server włączony");
});
//app.js
const loginRoute = require("./api/routes/loginRoute");
const registerRoute = require("./api/routes/registerRoute");
const verify = require("./autorization/verify");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/", (req, res, next) => {
console.log(req.method, req.query, req.body);
next();
});
app.use("/", loginRoute);
app.use("/", registerRoute);
app.use(verify);
based from your screenshot, there's a CORS issue. You can overcome that using
https://github.com/expressjs/cors middleware
var cors = require('cors');
app.use(cors());
or enable CORS for the specific route only
app.use('/', cors(), registerRoute);
registerRoute:
const express = require('express');
const router = express.Router();
const register = require('../../mongo/register');
router.post('/register',register);
module.exports = router;
register.js:
const mongo = require('./database');
const User = require('../api/patterns/user');
const register = (req,res)=>{
const toSave = new User(req.body);
User.findOne({name: req.body.name},(err,name)=>{
if(err) throw err;
if(!name){
toSave.save( (err)=> {
if (err) throw err;
console.log('user zapisany');
});
}else{
console.log('juz taki istnieje');
}
});
};
app.js:
const loginRoute = require('./api/routes/loginRoute');
const registerRoute = require('./api/routes/registerRoute');
const verify = require('./autorization/verify');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', (req,res,next)=>{console.log(req.method, req.query, req.body);
next();});
app.use('/', loginRoute);
app.use('/', registerRoute);
app.use(verify);
module.exports = app;
It still returns empty objects :(

Categories

Resources