Open wangjs-jacky opened 8 months ago
使用三种方式发送网络请求:
REST client
发送 POST
请求。
POST /d HTTP/1.1
HOST: localhost:7000
Content-Type: application/x-www-form-urlencoded
loginId=admin&loginPwd=12345
2. 使用原生表单发送 `urlencode` 请求,发送 `POST` 请求。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form表单的示例</title>
</head>
<body>
<form action="localhost:7000/d" method="post">
<p>
账号:<input type="text" name="loginId">
</p>
<p>
密码: <input type="text" name="loginPwd">
</p>
<button type="submit">登录</button>
</form>
</body>
</html>
url
发送 GET
请求。
直接地址栏输入url
localhost:7000/a
,浏览器以纯文本
形式显示。localhost:7000/b
,浏览器以 html
形式显示。localhost:7000/c
,浏览器以附件
形式显示。以 express
框架示例,监听 7000
端口。
const app = require("express")();
const bodyParser = require("body-parser");
const text = `<h1>两只老虎爱跳舞</h1>
小兔子乖乖拔萝卜
我和小鸭子学走路
童年是最美的礼物`;
const PORT = 7000;
// 配置 body-parser 中间件
// Content-Type: application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// 配置 body-parser 中间件
// 解析: Content-Type: application/json
app.use(bodyParser.json());
/* 解析响应体:text/plain */
app.get("/a", (req, res) => {
res.set("Content-Type", "text/plain; charset=utf-8");
res.end(text);
});
/* 解析响应体:text/plain */
app.get("/b", (req, res) => {
res.set("Content-Type", "text/html; charset=utf-8");
res.end(text);
});
/* 下载文件 */
app.get("/c", (req, res) => {
res.set("Content-Type", "text/plain; charset=utf-8");
res.set("Content-Disposition", "attachment; filename=song.txt");
res.end(text);
});
/* POST请求测试 */
app.post("/d", (req, res) => {
console.log("sss", req.body);
/* console.log("loginId", req.body.loginId); // 输出 "admin"
console.log("loginPwd", req.body.loginPwd); // 输出 "123123" */
res.end("success");
});
app.listen(PORT, () => {
console.log(`server started: ${PORT}`);
});
观察响应结果如下:
访问:localhost:7000/a
,以纯文本形式显示。
访问:localhost:7000/b
,以 html
形式显示。
访问: localhost:7000/c
,以附件形式下载,附件名称为 song.txt
以 REST Client
发送 POST
请求
使用 html
元素 form
发送 POST
请求
不同的
Content-Type
响应内容不同:text/html
:html文档,浏览器通常会将响应体作为页面进行渲染text/javascript
或application/javascript
:js代码,浏览器通常会使用JS执行引擎将它解析执行text/css
:css代码,浏览器会将它视为样式image/jpeg
:浏览器会将它视为jpg图片application/octet-stream
:二进制数据,会触发浏览器下载功能attachment
:附件,会触发下载功能