node js express app.get and app.post does not work - javascript

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too
is it replaced with something in the newer versions of express or something?
here is my code:
const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
//next line does not work
//if I use app.use it will work fine
app.get("/product",(req,res)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req,res)=>{
res.send("<h1>done</h1>")
})
app.listen(3000);

Your code is working fine. For the print body, you should have to use bodyParser in express js.
const express = require('express');
let app = express();
var bodyParser = require('body-parser')
app.use('/addp', (req, res, next) => {
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({ extended: true }));
app.use(
bodyParser.json({
limit: "250mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "250mb",
extended: true,
parameterLimit: 250000
})
);
app.get("/product", (req, res) => {
res.send("Get Request")
})
app.post("/product", (req, res) => {
console.log("-------------")
console.log(req.body);
console.log("-------------")
res.send("Post Request")
})
app.use('/', (req, res) => {
res.send("<h1>done</h1>")
})
app.listen(3000);

It is this:
app.route('/product/').get(function (req, res) {
If u want to add multiple routes let's say api, u will do this:
In some module api.js:
const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});
Then let's say your server:
app.use('/api', apiRoutes);

Related

Node.js using multer, res.file returns undefined

const app = require('express')();
const PORT = 8080;
const multer = require('multer')
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.listen(
PORT,
() => console.log(`it's alive on http://localhost:${PORT}`)
)
app.post('/user/self/pic', (multer({
dest: '../uploads'
}).single('image'), (req,res) => {
console.log(req.file)
}))
I'm building this most basic app using node.js. There's no front end implementation as our instructor doesn't allow any. Normally req.file will return basic info of the post request, but I tried many times and I'm getting undefined.
It seems there is a miss using in parentheses, try it:
app.post('/user/self/pic', multer({ dest: '../uploads' }).single('image'), (req, res) => {
console.log(req.file);
});
And it is a better version:
const uploader = multer({ dest: '../uploads' }).single('image');
app.post('/user/self/pic', uploader, (req, res) => {
console.log(req.file);
});

ExpressJS redirect index.html

JS,
I have an express app with some routes. When my router doesn't match any route it will display index.html instead of going to route '/*' and redirect to a specific route.
I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1.
Maybe I can do something with express-static but I don't know how.
And if I name my file home.html instead of index.html it's work perfectly.
Here is a small piece of my code :
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');
const port = 3080;
let csrfProtection = csrf({ cookie: true })
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
res.status(403).json({error: "Invalid CSRF Token"});
})
app.post('/roles', csrfProtection, (req, res) => {
/*...*/
});
app.get('/test', csrfProtection, (req, res) => {
/*...*/
});
app.all('/*', csrfProtection, (req,res) => {
if(Object.keys(req.query).length == 0) {
res.redirect("https://my-domain.com/test?id=1");
}
res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
My files structure is :
home
static
css
js
index.html
index.js
At the request for https://my-domain.com, write res.redirect('/foo/bar'), where /foo/bar is the url you want to redirect to.
See Official Documentation For res.redirect(): http://expressjs.com/en/api.html#res.redirect

Express route isn't executed when JSON file is requested

I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));

req.body returns empty on post

I'm pretty new to Express. not sure what I did wrong...
Here's a quick mockup of my situation.
app.js
const app = express();
const bodyParser = require('body-parser')
const port = 3000;
app.set('view engine', 'pug');
app.use('/static', express.static('./public'));
const urlEncoded = bodyParser.urlencoded({ extended: false });
const jsonParser = bodyParser.json();
app.get('/', (req, res) => {
res.render('index')
});
app.get('/form', (req, res) => {
res.render('form');
});
app.post('/', urlEncoded, (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`This app is listening on localhost:${port}`);
});
form.pug
block content
form(action="/" method="post")
label(for="name")
input(for="name" id="name")
input(type="submit")
the result in the console is an empty object.
You are confusing between id and name tag.The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted and this is what you are missing in your html form . So, just add a name attribute.
block content
form(action="/" method="post")
label(for="name")
input(for="name" id="name" name = "name")
input(type="submit")

When using ExpressJS and body-parser req.body is empty

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
oracledb.autoCommit = true;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
router.use('/' , function(req, res , next) {
console.log('Something is happening.');
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/insert')
.post(function(req, res) {
console.log(req.body);
console.log(req.body.c1);
console.log(req.body.c2);
});
app.use('/api', router);
app.listen(port);
In the example above ,when I try to log req.body it is returned as empty along with any of its properties.
EDIT: Maybe unrelated but when I try to test this REST API with a extension like Postman , it just keeps processing indefinately. ( Same thing happens with extension called DHC Rest)

Categories

Resources