- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 317字
- 2021-07-02 19:28:51
Handling POST data
One of the most common REST methods used in network applications is POST. According to the REST specification, a POST is not idempotent, as opposed to most of the other well-known methods (GET, PUT, DELETE, and so on) that are. This is mentioned in order to point out that the handling of POST data will very often have a consequential effect on an application's state, and should therefore be handled with care.
We will now discuss the handling of the most common type of POST data, that which is submitted via forms. The more complex type of POST—multipart uploads—will be discussed in Chapter 4, Using Node to Access the Filesystem.
Let's create a server which will return a form to clients, and echo back any data that client submits with that form. We will need to first check the request URL, determining if this is a form request or a form submission, returning HTML for a form in the first case, and parsing submitted data in the second:
const http = require('http');
const qs = require('querystring');
http.createServer((request, response) => {
let body = "";
if(request.url === "/") {
response.writeHead(200, {
"Content-Type": "text/html"
});
return response.end(
'<form action="/submit" method="post">\
<input type="text" name="sometext">\
<input type="submit" value="Send some text">\
</form>'
);
}
}).listen(8080);
Note that the form we respond with has a single field named sometext. This form should POST data in the form sometext=entered_text to the path /submit. To catch this data, add the following conditional:
if(request.url === "/submit") {
request.on('readable', () => {
let data = request.read();
data && (body += data);
});
request.on('end', () => {
let fields = qs.parse(body);
response.end(`Thanks for sending: ${fields.sometext}`);
});
}
Once our POST stream ends we parse the body using Querystring.parse, giving us a key/value map from which we can pluck the value of the form element with name sometext, and respond to the client that we have received their data.
- FreeSWITCH 1.2
- MERN Quick Start Guide
- 異構(gòu)基因共表達網(wǎng)絡(luò)的分析方法
- SD-WAN架構(gòu)與技術(shù)(第2版)
- Go Web Scraping Quick Start Guide
- 面向云平臺的物聯(lián)網(wǎng)多源異構(gòu)信息融合方法
- Building RESTful Web Services with Spring 5(Second Edition)
- Mastering TypeScript 3
- 城域網(wǎng)與廣域網(wǎng)(第2版)
- C/C++串口通信:典型應(yīng)用實例編程實踐
- Windows Server 2012 Hyper-V虛擬化管理實踐
- 物聯(lián)網(wǎng)頂層設(shè)計與關(guān)鍵技術(shù)
- Getting Started with Memcached
- 移動互聯(lián)網(wǎng)新思維
- RestKit for iOS