上QQ阅读APP看书,第一时间看更新
How to do it...
Two forms will be displayed to the user, both of them will send data to our web server application encoded in two different ways. The first one is a URL encoded form while the other one will encode its body as plain text.
- Create a file named parse-form.js
- Include the body-parser NPM module. Then, initialize a new ExpressJS application:
const express = require('express') const bodyParser = require('body-parser') const app = express()
- Include the body-parser middleware functions to handle URL encoded requests and text plain requests:
app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.text())
- Add a new route method to handle GET requests for path "/". Serve HTML content with two forms that submit data using different encodings:
app.get('/', (request, response, next) => { response.send(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>WebApp powered by ExpressJS</title> </head> <body> <p role="application"> <form method="post" action="/setdata"> <input name="urlencoded" type="text" /> <button type="submit">Send</button> </form> <form method="post" action="/setdata"
enctype="text/plain"> <input name="txtencoded" type="text" /> <button type="submit">Send</button> </form> </p> </body> </html> `) })
- Add a new route method to handle POST requests for path "/setdata". Display on terminal the content of request.body:
app.post('/setdata', (request, response, next) => { console.log(request.body) response.end() })
- Listen on port 1337 for new connections:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a terminal and run:
node parse-form.js
- In your web browser, navigate to:
http://localhost:1337/
- Fill the first input box with any data and submit the form:
- In your web browser, navigate back to:
http://localhost:1337/
- Fill the second input box with any data and submit the form:
- Check the output in the terminal