wangjs-jacky / examples-collection

0 stars 0 forks source link

浏览器用户代理能力:如何根据不同的响应结果展示不同的内容 #2

Open wangjs-jacky opened 8 months ago

wangjs-jacky commented 8 months ago

不同的 Content-Type 响应内容不同:

wangjs-jacky commented 8 months ago

使用三种方式发送网络请求:

  1. 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>
  1. 使用 url 发送 GET 请求。 直接地址栏输入url
    • 输入localhost:7000/a ,浏览器以纯文本形式显示。
    • 输入localhost:7000/b ,浏览器以 html 形式显示。
    • 输入localhost:7000/c ,浏览器以附件形式显示。
wangjs-jacky commented 8 months ago

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}`);
});

观察响应结果如下:

  1. 访问:localhost:7000/a ,以纯文本形式显示。

  2. 访问:localhost:7000/b ,以 html 形式显示。

  3. 访问: localhost:7000/c ,以附件形式下载,附件名称为 song.txt

  4. REST Client 发送 POST 请求

  5. 使用 html 元素 form 发送 POST请求