NodeJS response is not parsed by express or bodyparser - javascript

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
// app.use(express.urlencoded({extended:false}));
// app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json())
router.get('/add-product', (req, res, next) => {
res.send('<form action="/product" method="POST"><input type="text" id="fname" name="fname"><br><input type="submit" value="Submit"></form>')
})
the response isn't parsed .. I tried 1k things .. Nothing works... i still receive undefined
i tried both variants **app.use(bodyParser.urlencoded({extended:true})); and app.use(express.urlencoded({extended:false})); + app.use(bodyParser.json()) and app.use(express.json());**
What's to do ? thank you in advance

you should have app.get and not router.get
See here

Related

express js cannot get / register

I faced this issue where it gave me Cannot GET /register, but why get for the login.html is working and not register, do I'm missing something here ? thank you guys for your help in advance. Here is the router
const express = require('express');
const router = express.Router()
const bcrypt = require('bcrypt');
const user = require('../models/user.js')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register'),(req,res)=>{
res.render('register')
}
router.post('/register'), (req, res) =>{
};
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const sequilize = require('./database/db.js')
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
Issue is here
router.get('/register'),(req,res)=>{
res.render('register')
}
it should like
router.get('/register',(req,res)=>{
res.render('register')
}
you have added ")" after register

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

hey guys i know this has been asked before but i do not understand it ,,
so anyone help please
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
const api = require('./server/routes/api');
const path = require('path');
app.use(express.static(path.join(__dirname, 'dist/todo')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/todo/index.html'));
})
app.listen(port, () => console.log('server started'));
the error i get when starting the server
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

Express js router not working

This is my home.js code
// import modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require ('cors');
var path = require ('path');
var app = express();
const route= require('./routes/route');
//port no
const port =3000
app.use(cors());
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
app.use('./api', route);
//testing server
app.get('/', (req,res)=>{
res.send('foober');
})
app.listen(port,()=>{
console.log('server started at port:' + port);
});
And this the route.js code
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res, next )=>{
res.send('retrieve contact');
});
module.exports =router;
But whenever I run 'localhost:3000/api/contacts' i get 'Cannot GET /api/contacts' error. I am very new at this, what am I doing wrong?
A dot in an url is there to seperate domains, if your route is mounted at ./api you would have to visit yourserver.com./api which won't work as the url is invalid.

Cannot POST with ExpressJS and CSRF

I'm newbie with node.js and express and I'm trying to protect some url's with a token. I generate the token correctly but when I post a form with this token I've got an error in my browser with this text "Cannot POST /process" where /process is the url where I send the data from my form. In my console I haven't any error. So, I don't know what is happend or what am I doing wrong :(
The code is divided in three files, main file called (index.js) where I require the second file (routes-api.js) and the html file with the form.
index.js
//Creación de un servidor con express
const express = require("express");
const app = express(); //Inicializamos express
//Accedemos a otros módulos
const morgan = require("morgan");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const cookieParser = require('cookie-parser');
//Accedemos a propiedades de configuración
const config = require("./config");
//Rutas
const routes = require("./routes");
const routesAPI = require("./routes-api");
//Settings
app.set("app-name", config.server);
app.set("port", config.port);
app.set("super-secret", config.secret);
//Middlewares
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan("dev")); //Log request to the console
app.use(cookieParser());
app.use((req, res, next) => {
console.log("Pasamos por la segunda función!!!");
next();
});
//Routing
app.use("/api", routesAPI);
app.use(routes);
//Server
app.listen(app.get("port"), () => {
console.log("Servidor " + app.get("app-name") + " escuchando!!!");
}); //Creamos el servidor con express
route-api.js
const csrf = require('csurf');
const path = require("path");
const bodyParser = require("body-parser");
const express = require("express");
const router = express.Router();
// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });
router.get("/", csrfProtection, (req, res) => {
console.log("crsf: " + req.csrfToken());
res.sendFile(path.join(__dirname + '/send.html'), { csrfToken: req.csrfToken() });
});
router.post('/process', parseForm, csrfProtection, function(req, res) {
console.log("csrf: " + req.body._csrf + " color: " + req.body.favoriteColor);
res.send('data is being processed');
});
module.exports = router;
send.html
<form action="/process" method="POST">
<input type="text" name="_csrf" value="{{csrfToken}}">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
What am I doing wrong to get the error "Cannot POST /process" when I send the form to the server?

Saving data to json using nodejs and cointicker

Im learning nodejs and I'm creating a server to get the price of cryptocurrencies using a npm called Coin-Ticker. I want to use the data I'm getting in an Angular app but it's not displaying the data in the html. This is my code:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Thanks for your help!
It is because coin ticker returns the json in the then so when you are doing res.status(200).json(posts.data); it is returning undefined. just replace that with res.status(200).json(posts) and it should work
Also you can not do router.get((req, res) => {
you need a path before this. I tried this code with
router.get('/convert', (req, res) => { and with the changes above it worked

Categories