了解 HTTP 基础知识

发布日期:2026-07-11 11:46:03   来源 : 杭州电子商务研究院    浏览量 :8
杭州电子商务研究院 发布日期:2026-07-11 11:46:03  
8

介绍

我们生活在一个被信息包围的世界,互联网是我们与信息之间的主要接口。我们使用网站、网络应用程序、移动应用程序等,几秒钟内,我们就能非常轻松地获取信息。简单来说,我们在谷歌上输入“https://www.google.com”,只需单击一下,就能获得谷歌页面。你有没有想过它是如何工作的?你想知道吗?如果你在这里,我只能假设答案是“是的”,我们将对其进行描述。

HTTP 代表超文本传输​​协议

Web 应用程序通过交换信息来工作。“交换信息,怎么可能?”每当您浏览网页时,您的浏览器都会发送 HTTP 请求消息,请求 HTML 页面、图像、脚本和样式表。Web 服务器通过返回包含所请求资源的响应消息来处理这些请求。HTTP 是通信的桥梁;它使互联网上的信息交换成为可能。HTTP 是桥梁,但对于通信,我们使用 WWW (万维网)来负责客户端和服务器之间的连接。

在本指南中,我们将了解 HTTP 以及如何在客户端和服务器之间交换信息或数据。

HTTP 如何工作

客户端和服务器之间的所有通信都是通过请求和响应进行的。HTTP 有 HTTP 请求和 HTTP 响应来进行通信。

底层发生的情况如下:

  • 浏览器(客户端)向网络发送 HTTP 请求。
  • Web 服务器接收请求。
  • 服务器运行一个应用程序来处理请求。
  • 服务器向浏览器返回 HTTP 响应(作为输出)。
  • 浏览器收到响应。
  • 你就可以在浏览器中看到你想要的数据了。

入门

在开始本指南之前,我会告诉你我们正在使用Angular7来处理 HTTP。因此,请确保你的系统中有Node.js ;如果没有,请从此处安装它。

接下来需要做的是安装 Angular;让我们通过npm安装它。

      npm install -g @angular/cli
    

注意:建议使用 IDE;一些最佳选择是 Visual Studio Code 或 JetBrains WebStorm。

Angular 是一个 JavaScript 框架,它允许您创建响应式单页应用程序。这是一个领先的前端开发框架,由 Angular 定期更新。Angular 7 完全基于组件。了解 HTTP 大有裨益,因此我们使用 Angular 应用程序来了解 HTTP。

跳到代码

我假设您现在已经设置了 Angular 7,那么让我们进入一个简单的示例代码。

步骤 1:开始一个新项目

由于 Angular 是一个框架,我们需要遵循框架的一些标准。要在 Angular 中创建新项目,请使用命令ng new project_name。我将我的项目命名为HTTP tutorial

      ng new HTTP tutorial
    

这将创建一个包含以下内容的教程目录:

      HTTP tutorial
├── node_module               -- Installed Angular packages available in the project
└── src                       -- Contains the main code files.
    ├── app folder            -- Contains the files for app components
    ├── app.component.css     -- Cascading style sheets code for app component.
    ├── app.component.html    -- The HTML file related to the app component
    ├── app.component.spec.ts -- Unit testing file related to app component.
    ├── app.component.ts      -- Write view logic behind the component.
    └── app.module.ts         -- Includes all the dependencies for the website.
├── package.json              -- npm configuration file include packages version
├── package-lock.json         -- Auto-generated and modified file.
├── angular.json              -- Configuration file related to your angular application
├── .gitignore                -- File is related to the source control git.
├── .editorconfig             -- Maintain consistency in code editors to organize.
├── assets folder             -- Placeholder for resource files.
├── environments folder       -- Hold the environment configuration constants
├── browserlist               -- Adjusts the CSS to support a list of defined browsers.
├── favicon.ico               -- Small icon that appears next to the browser tab
├── index.html                -- Entry file holds the high-level container application.
├── karma.config.js           -- Config file for the Karma Test Runner
├── main.ts                   -- The main ts file that will first run.
├── polyfills.ts              -- Used to cover whatever feature missing from browser.
├── styles.css                -- Global CSS file which is used by an application.
├── tests.ts                  -- Use to traverse all the unit tests in the application
├── tsconfig.json             -- Typescript compiler configuration file.
├── tsconfig.app.json         -- Override the tsconfig.json file with app configurations.
├── tsconfig.spec.json        -- Override the tsconfig.json file with app unit test configurations.
    

步骤 2:创建第一个用于处理 HTTP 的 Angular 应用程序

设置 HttpClient:这是在 src/app/app.module.ts 中导入 HttpClientModule 的第一步。

      import { HttpClientModule } from '@angular/common/http';
@NgModule({
    declarations: [
        AppComponent
    ],
imports: [BrowserModule,HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule { }
    

创建一个类模型:使用命令ng generate class class_name。我将类名命名为employee

      ng generate class employee
    

生成类后,您必须添加对象:

      export class Employee {
    id: number;
    employee_name: string;
    employee_salary:number;
    employee_age:number;
}
    

对于 HTTP URL 调用,我们需要 Angular 中的服务文件。使用命令ng generate service service_name。我将类名命名为apicall

      ng generate service apicall
    

为什么要有服务?

组件不应直接获取或保存数据,当然也不应该故意提供虚假数据。它们应该专注于呈现数据并将数据访问委托给服务。这里我们使用 apicall.service.ts。

生成 apicall.service.ts 后,导入 HTTP 客户端并在构造函数中初始化它,如下所示。

      import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Employee } from './employee';
    

在构造函数中:

      constructor(private httpClient: HttpClient) {}
    

要在 Angular 中运行,可以使用以下命令:

      ng serve
    

如果您想直接在打开的浏览器中运行,请使用以下命令:

      ng serve --open
    

步骤 3:我们的第一个 HTTP 请求

HTTP 定义了一组请求方法来指示针对给定资源要执行的所需操作。

让我们逐一看看提出请求的所有方法及其实现。

GET 方法: GET 方法请求指定资源的表述。使用 GET 的请求应仅检索数据。

按照以下代码获取员工的所有记录。

apicall.service.ts中:

      public nextPage: string = "";
public getEmployes(url?: string){
    return this.httpClient.get<Employee[]>(`http://dummy.restapiexample.com/api/v1/employees`);
}
    

app.component.ts中:

      getEmployeeList(){
    this.apiService.getEmployes().subscribe((res)=>{ this.apiService.getEmployes(this.apiService.nextPage).subscribe((data:Employee[]) => {
        console.log(data);
        });
    });
}
    

app.component.html中:

      <table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Salary</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let emp of employees">
            <td>{{emp.employee_name}}</td>
            <td>{{emp.employee_salary}}</td>
            <td>{{emp.employee_age}}</td>
            <td >
                <button (click)="deleteEmployeeData(emp.id)">Delete</button>
            </td>
        </tr>
    </tbody>
</table>
    

从上面的代码中,您的请求和响应如下所示:

请求的 URL:

网址:https://dummy.restapiexample.com/api/v1/employees

服务器响应:

      {
    "id":"81164"
    

根据 ID 获取记录:

按照以下代码获取员工的单条记录。

apicall.service.ts中:

      public getEmployeeById(id: number){
    return this.httpClient.get(`http://dummy.restapiexample.com/api/v1/employee/${id}`);
}
    

app.component.ts中:

      getEmployee(id:number){
    this.apiService.<span class="hljs-title functio
以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据