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?
Related
The server is running without any errors. but the page is constantly loading and stays on. Then I get the error 'Incomplete response received from application.
Console Img
App.js
const express = require('express')
const exphbs = require('express-handlebars')
const app = express()
const hostname = '127.0.0.1'
const port = process.env.PORT || 3000
const mongoose = require('mongoose')
const mongo = require('mongodb')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const expressSession = require('express-session')
const connectMongo = require('connect-mongo')
const methodOverride = require('method-override')
const limit = require('./helpers/limit').limit
const truncate = require('./helpers/truncate').truncate
const paginate = require('./helpers/paginate').paginate
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://siber_haber:myapppass#siberhabercomm.sspd3.mongodb.net/Siberhabercomm?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
const mongoStore = connectMongo(expressSession)
app.use(expressSession({
secret: 'testo test',
resave: false,
saveUninitialized: true,
store: new mongoStore({ mongooseConnection: mongoose.connection })
}))
app.use(fileUpload())
app.use(express.static('public'))
app.use(methodOverride('_method'))
// handle-bars helpers
const hbs = exphbs.create({
helpers: {
limit: limit,
truncate: truncate,
paginate: paginate
}
})
app.engine('handlebars', hbs.engine)
app.set('view engine', 'handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// DISPLAY LINK MIDDLEWARE
app.use((req, res, next) => {
const {userId} = req.session
if(userId) {
res.locals = {
displayLink : true
}
} else {
res.locals = {
displayLink : false
}
}
next()
})
app.use((req, res, next) => {
res.locals.sessionFlash = req.session.sessionFlash
delete req.session.sessionFlash
next()
})
const main = require('./routes/main')
const post = require('./routes/posts')
const users = require('./routes/users')
const admin = require('./routes/admin/index')
app.use('/', main)
app.use('/posts', post)
app.use('/users', users)
app.use('/admin', admin)
app.listen(port, hostname, () => {
console.log(` Server Çalışıyor http://${hostname}:${port}`)
})
Please help me understand where the error is
i think the error is from the database code. i'm not so sure.
Node version v10.24.1
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.'));
hello im using express for server everything is working find but i am not receiving my data from post method.Iam using body-parser too
const express = require("express")
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req,res)=>{
var data = req.body
res.send(req.body)
})
Here is a 100% working code. If it doesn’t work, then tell me how do you make a POST request?
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post("/signup", (req, res) => {
var data = req.body
console.log(data)
res.send(req.body)
})
app.listen(3000)
Front-end:
axios.post('http://localhost:3000/signup', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I've created simple Express.js Rest API with MongoDB. I am using this package: https://www.npmjs.com/package/api-query-params and everything works very well except for one thing. I have a URL like this:
localhost/properties/?town=LONDON
this returns all properties from London, the problem is with this is the next thing, I need to put capitalize value (LONDON), I am trying to achieve that this value can be lowercase (london), so final URL will be like this:
localhost/properties/?town=london
My route:
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
const aqp = require ('api-query-params');
router.get('/all', (req, res, next) => {
const { filter, skip, limit, sort, projection, population, casters } = aqp(req.query, {
casters: {
lowercase: val => req.query.toLowerCase(),
},
});
Property.find(filter)
.skip(skip)
.limit(limit)
.sort(sort)
.select(projection)
.populate(population)
.exec((err, properties) => {
if (err) {
return next(err);
}
res.send(properties);
});
});
module.exports = router;
And app.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
require('dotenv/config');
const mongoose = require('mongoose');
const propertyRoute = require('./routes/property');
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/properties', propertyRoute);
//routes
app.get('/', (req, res) => {
res.send('value');
});
mongoose.connect('linkdatabse', {
newUrlParser: true,
})
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
I've updated my route according to documentation: https://www.npmjs.com/package/api-query-params#add-custom-casting-functions
but still, this doesn't work
Can anybody try to help me with this, what am I doing wrong?
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 :(