Simple NodeJS RESTful API with post method and no database involved - javascript

Im very new to nodejs ive used an exmaple to write simple REST app, this is using GET method but im trying to use POST method with --data, for example
curl -X POST --data 'bla' http://localhost:port
i want it to return repsone "blabla"
im trying to see all kinds of exmaple but lots of them using databases and on this simple app i dont want any database involved,
appriciate if anyone can guide me or point me to a good example
**edit
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({
extended: true
}))
app.use((req, res, next) => {
console.log(new Date(), req.url, req.method)
next()
})
app.post('/', (req, res, next) => {
try {
if (req.body.data == 'bla'){
res.send("blabla")
}
} catch (error) {
next(error)
}
})
app.listen(3000)
it works without the "if" part, i must be missing something small here...

Related

Express middleware: res.statusCode doesn't accurately return the status code [duplicate]

This question already has answers here:
NodeJS Express = Catch the sent status code in the response
(2 answers)
Closed 2 years ago.
I have a fairly straight forward logging middleware function in an Express JS app:
app.use(function (req, res, next) {
const line = `${req.method} ${req.originalUrl} ${res.statusCode}`
console.log(line)
next()
})
And I have this route:
this.app.use('/404', function (req, res) {
res.sendStatus(404)
})
Which logs the following:
GET /404 200
With other routes it seems to always return 200.
How can I fix this so that it accurately logs status codes without changing routes?
Edit
My goal here was something quick to tell me if a route was hit and whether or not it succeeded. I don't want to have to edit all my routes to be compatible with it since I'll eventually replace it with an actual logging solution.
Depending of : https://expressjs.com/guide/error-handling.html
app.use('/404', function (req, res) {
console.error(err.stack);
res.status(404).send('not found!');
});
Also you can use http-errors module:
var createError = require('http-errors');
app.use(function(req, res, next) {
next(createError(404));
});
This still doesn't work for all routes but works for more of them:
this.app.use(async function (req, res, next) {
await next()
const line = `${req.method} ${req.originalUrl} ${res.statusCode}`
console.log(line)
})
Don't know your entire code, but this.app is not necessary. Directly use app.use.
Debug, while hitting, you request do not come within app.use('/404'), It might be serving path mentioned above it like app.use('/:variable'), so may be variable == 404.
Mention this type of static path topmost.

How to manage request data on entry file in node js

In Node Js, on the entry file e.g. index.js, How can I get requested data either as Form-data or Form-URL-encoded or Raw JSON data in middleware?
In my project, I am handling various API request,
Few requests contain file type so requesting as form-data.
Few requests do not contain file type so requests are coming as Form-URL-encoded.
Now the main problem is before routing, I need a specific field from req.body in the middleware.
But I am getting req.body as undefined.
For reference here is my index.js file:
const express = require('express');
const app = express();
app.use(express.raw());
app.use(express.urlencoded({ extended: false }));
app.use((req, res, next) => {
const routes_handler = require('./routes/index.js')(app, express, req);
next();
})
app.listen(3000, () => {
console.log("Server running at Port " + 3000);
});
and the routes/index.js file as follows:
module.exports = function (app, express, req) {
console.log(req.body);
//I need here data of req.body for all requests type (form data, URL-encoded, raw JSON)
app.post('/', function (req, res) {
console.log("Here I can get the requested body easily", req.body)
res.send('Hello World');
});
app.post('*', function (req, res) {
res.send({
code: 0,
message: 'No Content',
status_code: 204,
data: {
error: 'API not found!'
}
});
});
}
Also, I know for file type data, POSTMAN will send the request as Form-data, not as Form-url-encoded. So which I should choose Formidable or Multer?
The way you get all the data in index.js is by creating middlewares for your application, every time any routes that go into your application will be passed through this middleware.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
The below middleware will simply listen to all routes & adds up request time to request time, here goes the code
let express = require('express')
let app = express()
let bodyParser = require("body-parser")
app.use(bodyParser.json())
let requestTime = function (req, res, next) { // simply updating add the requestBody using the middleware
req.requestTime = Date.now();
req.json_body = req.body;
next()
}
app.use(requestTime) // requestTime is the middleware here
app.get('/', function (req, res) {
var responseText = 'Hello World!<br>'
responseText += '<small>Requested at: ' + req.requestTime + '</small>'
res.send(responseText)
})
app.listen(3000)
Few things to note here
Always add interceptor above all routes
Don't forget to add next() inside the middleware, else it will not go to the next route.
Now, coming to the second part of your question which is accessing body,formdata, etc
You can use body-parser npm module to achieve that, something like this
Starting from Express 4, body-parser comes inbuilt with it, so you can try out something
app.use(express.json());
app.use(
bodyParser.urlencoded({
extended: false
})
);
Now, the last bit, you don't need Multer for formdata, but for file upload like multipart/form-data you will need this. Both are good in their own ways, I would go for Multer.
Hope this will help you :)
I believe the body-parser module is your answer.
https://www.npmjs.com/package/body-parser
Add the following line before the routes in your index.js after installing the body-parser package.
app.use(bodyParser.json())

how to use passportjs middleware in a restify application

I am trying to use passport.js to set up authorization in an api. I am having trouble checking if a user is already logged. In expressjs I would do something like:
router.get('/is_logged_in',
passport.authenticate('jwt', { session: false }),
function (req, res, err) {
...
}
that is, in expressjs you can add the middleware passport.authenticate(...),
Can this be done with restify?, for instance if I have the route:
server.get('/is_logged_in', (req, res, next) => {
...
});
Where do I put the middleware? (or is this supposed to be done differently?) I can not add it as a second parameter for what I understand.

Expressjs rerouting

I need to make routing flexible for slashes, for example
app.get('/home/pages')
router must handle
////home///pages
/home/pages////
etc...
requests.
Currently I have one idea to implement this, but for that I need to know how to reroute request via middleware,
If you can answer this question or suggest something else I will be grateful to you.
Also please don't suggest using regex for defining routers, because project is already done and there is a lot of already defined routes.
You need to rewrite url in a middleware:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
req.url = req.url.replace(/\/+/g, '/');
next();
});
app.get('/home/pages', function (req, res) {
res.send('some pages');
});
app.listen(3000);

How protect a RestFul Api in Nodejs?

Nowadays i am using https://github.com/baugarten/node-restful wich helpme to work in an API, the question is?
I am working in Express framework, are there a way to protect the "GET" request from other site to mine.
I use the CSRF from express but only work by POST,PUT,DELETE methods with a message of FOrbidden 403 when treat make anithing since curl in console but if I make a curl toward a Get method curl localhost:3000/posts that giveme an array with all the posts.
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(app.router);
What you advice me? are there other modules to work an Api better? How can protect an Api in nodejs? What are the best practices that a haver to learn?
Thanks by your Help.
Try Express middleware which is designed to do so. For example:
var express = require('express');
var app = express();
// simple middle ware to protect your URI
app.use(function(req, res, next){
if (req.method == 'GET') {
if (!req.locale.token) { res.send(403); } // custom to fit your policy
else if (req.protocol !== "https") {res.redirect("your-secure-url");}
else { next(); }
}
});

Categories