The blog based on Node.js server.
In front-end, we have several types to send a request to server, most of the time, we use 3 commonly below:
- application/json
- application/x-www-form-urlencoded
- multipart/form-data
application/json
GET
client
1 | $.ajax({ |
Check the request header in network panel in Chrome dev-tool, you will see the request URL turn to http://domain/upload?{"test":"wuyuchang","passowrd":"chang"}, it’s because GET request always append data to the request URL.
1 | Request URL:http://domain/upload?{"test":"username","passowrd":"password"} |
server
In server side, you can read the header that client send throw req.headers, and URL throw req.url, then you just compile analysis the parameter after question mark.
1 | http.createServer((req, res) => { |
POST
Client
For client, you just change the request method from ‘GET’ to ‘POST’.
Server
In server side, you can’t get content that client send directly, it’s send throw buffer, so you have to receive it by listen it throw req.on(‘data’)
1 | http.createServer((req, res) => { |
It’s convenient to get JSON data throw this way.
application/x-www-form-urlencoded
GET
Client
Same with above, just change the contenType to ‘application/x-www-form-urlencoded’, the jQuery wouldn’t add contentType automatic if you set method as ‘GET’.
server
1 | http.createServer((req, res) => { |
POST
jQuery set contentType as ‘application/x-www-form-urlencoded’ if you send request throw ‘POST’ method.
server
1 | http.createServer((req, res) => { |
multipart/form-data
multipart/form-data always used to send a file, of course, you also can send form without file.
GET
It’s same with below, the different is that if you send a file to server, the server can’t accept it.
POST
Client
1 | <form action="/upload" method="POST" enctype="multipart/form-data"> |
the request header is different
1 | Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryuyeyXEbnVwhZJcl6 |
the value of boundary is random.
Server
In server side you can compile it, but it’s complex, you can import a package name of ‘formidable’.