https://ciphertrick.com/2015/02/25/get-post-requests-in-node-js-using-express-4/
In this tutorial we will learn how to handle GET & POST request in node.js using Express 4. Using Express 4 we can easily handle requests. And we have also used Mysql to Fetch and post data from database.
SQL file can be found along with the downloaded code.
Let’s start with installing dependencies and then the code,
Will going to use following node modules for handling session.
I have created a package.json file that will install all required dependencies. have a look,
By typing following command you can install dependencies,
npm install
Note:You must also have MySQL installed if you are working locally.
First will include require node modules and http server.
Also we have done connection of Mysql for GET & POST data.
In GET request we are basically fetching data/values from database and showing as JSON format.See below code,
Using “app.get(“/url”,function)” we can do URL routing and based on that will fetch data as required.
And “connection.query(“Query”,function)” will used for writing query and in callback will get required data as you can see above code.
In POST request we are posting data/values and based on that we will validate and send response as JSON.
I’ve created a login API for demo purpose. See below code,
Using “app.post(“/url”,function)” we can do URL routing and based on that will fetch or post data as required.
And First will get posted data by using “req.body” (i.e : req.body.email & req.body.password ).
Now use that data in query to check whether user is exist or not and based on that it will return response.
First check whether you have installed Node.js or not.
Then install all required dependencies (i.e : express, express-session & body-parser ) by typing following command in terminal,
npm install
Now, run the server using following command.
node server.js
And now go to browser and hit “localhost:8080″.