const express = require('express');
let router = express.Router();
router.get('/add-product',(req, res, next)=>{
res.send('<form action="/try" method="POST"><input type="text" name="title"><button type="submit">Sub,it</button> </form>');
});
package.json
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"funding": "^1.0.9"
It shows the error "unresolved function or method get()"
I even install express and body-parser
You should use express instead of express.Router()
let router = express();
If example will not help you please specify you app starting file
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
const routerProducts = express.Router()
// middleware that is specific to this router
routerProducts.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the add-product route
routerProducts.post('/add-product', function (req, res) {
res.send('products create')
})
// define the get-product route
routerProducts.get('/get-product', function (req, res) {
res.send('products get')
})
app.use('/products', routerProducts )
app.listen(3000, () => console.log('server started'));
call GET: http://127.0.0.1:3000/products/get-product
Related
I'm building a server with Node and Express, using handlebars as views. My controller contains the system logic functions, which receive the request and response objects as parameters and my Route, only makes the connection between the route and the controller. But I am not able to see the error to generate this error in the title.
My controller.js:
const router = express.Router();
exports.home = (req, res) => {
res.render('home', { entries: entries });
};
exports.Form = (req, res) =>{
res.render('form')
};
exports.FormFetch = (req, res) =>{
res.render('form-fetch')
};
My app.js:
const express = require('express');
const handlebars = require('express-handlebars');
const app = express();
app.engine('.hbs', handlebars.engine({
defaultLayout: 'main',
extname: '.hbs',
}));
app.set('view engine', '.hbs')
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var userRoute = require('./routes')
app.get('/', userRoute)
app.use('/new-entry', userRoute)
app.use('/new-entry-fetch', userRoute)
app.listen(3000, () =>{
console.log('Ok')
});
My routes.js:
const express = require('express');
const controller = require('./controllers/controllers');
const app = express();
const entries = [];
app.get('/', (req, res) => {
res.render(controller.home, { entries: entries });
});
app.get('/new-entry', (req, res) => {
res.render(controller.Form);
});
app.get('/new-entry-fetch', (req, res) => {
res.render(controller.FormFetch);
});
app.post('/new-entry', (req, res) => {
entries.push({
title: req.body.title,
content: req.body.body,
published: new Date()
});
res.redirect(303, '/');
});
module.exports = app
I have simply express server:
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const bodyparser = require('body-parser');
const app = express();
const hbs = exphbs.create({
defaultLayout: 'main',
extname: 'hbs'
});
const _PORT = process.env.PORT || 80;
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
app.set('views', 'views');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json({ type: 'application/*+json' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('./routers/login'));
serverStart();
async function serverStart(){
try{
app.listen(_PORT);
console.log('[SERVER] Server is listening port ' + _PORT + ' now.');
}catch(error){
console.log(error);
}
}
And simply router:
const { Router } = require('express');
const router = Router();
router.get('/', async (req, res) => {
res.render('login', {
title: 'main page'
});
});
router.post('/', async (req, res) => {
console.log(req.body);
});
module.exports = router;
Why 'req.body' is always empty?
I tried to send POST query from "Postman", but it isn't work.
It's working only with x-www-form-urlencoded query, but I want to send json query.
P.S. Sorry for my english.
UPD: postman screenshot
link
I've been try your code and it's working fine, you only have to change your code:
app.use(bodyparser.json({ type: 'application/*+json' }));
With this code below:
app.use(bodyparser.json({ type: 'application/json' }));
Note: If you're use the latest version of express, then you should not to install body-parser, Because body-parser is already included.
So, you can use this code below:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
I hope it can help you.
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))
Error: "node_modules/express/lib/router/index.js:458 Router.use() requires a middleware function but got a Object at Function.use"
Code:
const express = require('express');
const bodyParser = require('body-parser');
const mustacheExpress = require('mustache-express');
const pgp = require('pg-promise');
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const students = require('./controllers/students.js');
const houses = require('./controllers/houses.js');
app.use('/houses', houses);
app.use('/students', students);
app.get('/', (req, res) => res.render('home/index'));
app.listen(port, () => { console.log("Server started on " + port); });
module.exports = router;
controllers/students.js:
This is the first file which is linked to the index.js
const router = require('express').Router();
const Students = require('../models/students.js');
router.get('/',
Students.findAll, (req, res) => {
res.render('students/index', {studentsData: res.locals.allStudentsData})
});
router.get('/:id', Students.findById, (req, res) => {
res.render('students/show', res.locals.showStudent)
});
module.exports = router;
controllers/houses.js:
This is the second file which is linked to the index.js
const router = require('express').Router();
const Houses = require('../models/houses.js');
router.get('/',
Houses.findAll, (req, res) => {
res.render('houses/index', {housesData: res.locals.allHousesData})
});
router.get('/:id', Houses.findById, (req, res) => {
res.render('houses/show', res.locals.showHouse)
});
module.exports = router;
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