
# 获取托管配置(Node.js SDK)
![](https://support.huaweicloud.com/sdk-nodejs-devg-obs/public_sys-resources/notice_3.0-zh-cn.png)
开发过程中，您有任何问题可以在GitHub上[提交issue](https://github.com/huaweicloud/huaweicloud-sdk-nodejs-obs/issues)，或者在[华为云对象存储服务论坛](https://bbs.huaweicloud.com/forum/forum-620-1.html)中发帖求助。
#### 功能介绍
OBS允许在桶内保存静态的网页资源，如.html网页文件、flash文件、音视频文件等，当客户端通过桶的Website接入点访问这些对象资源时，浏览器可以直接解析出这些支持的网页资源，呈现给最终用户。典型的应用场景有：
- 重定向所有的请求到另外一个站点。
- 设定特定的重定向规则来重定向特定的请求。
调用获取桶的网站配置接口，您可以获取指定桶的网站配置信息。
#### 接口约束
- 您必须是桶拥有者或拥有获取桶的网站配置的权限，才能获取桶的网站配置。建议使用IAM或桶策略进行授权，如果使用IAM则需授予obs:bucket:GetBucketWebsite权限，如果使用桶策略则需授予GetBucketWebsite权限。相关授权方式介绍可参见[OBS权限控制概述](https://support.huaweicloud.com/perms-cfg-obs/obs_40_0001.html)，配置方式详见[使用IAM自定义策略](https://support.huaweicloud.com/usermanual-obs/obs_03_0121.html)、[自定义创建桶策略](https://support.huaweicloud.com/usermanual-obs/obs_03_0123.html)。
- OBS支持的Region与Endpoint的对应关系，详细信息请参见[地区与终端节点](https://console.huaweicloud.com/apiexplorer/#/endpoint/OBS)。
 
#### 方法定义
```
ObsClient.getBucketWebsite(params)
```
#### 请求参数
表1BucketRequestInput 
| **参数名称** | **参数类型** | **是否必选** | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|:---|:---|:---|:---|
| Bucket   | string   | 必选       | **参数解释** **：** 桶名。 **约束限制：** - 桶的名字需全局唯一，不能与已有的任何桶名称重复，包括其他用户创建的桶。  - 桶命名规则如下： - 3～63个字符，数字或字母开头，支持小写字母、数字、"-"、"."。  - 禁止使用IP地址。  - 禁止以"-"或"."开头及结尾。  - 禁止两个"."相邻（如："my..bucket"）。  - 禁止"."和"-"相邻（如："my-.bucket"和"my.-bucket"）。    - 同一用户在同一个区域多次创建同名桶不会报错，创建的桶属性以第一次请求为准。   **取值范围：** 长度为3～63个字符。 **默认取值：** 无 |
   
#### 返回结果
表2返回结果 
| **参数类型**                                                                                                                                              | **描述**                                                                                  |
|:---|:---|
| [表3] 说明： 该接口返回是一个Promise类型，需要使用Promise、async/await语法处理。 | **参数解释：** 接口返回信息，详见[表3]。 |
   
 表3Response 
| **参数名称**        | **参数类型**                                       | **描述**                                                                                                                                                                               |
|:---|:---|:---|
| CommonMsg       | [ICommonMsg] | **参数解释：** 接口调用完成后的公共信息，包含HTTP状态码，操作失败的错误码等，详见[ICommonMsg]。                                                             |
| InterfaceResult | [表5]              | **参数解释：** 操作成功后的结果数据，详见[表5]。 **约束限制** **：** 当Status大于300时为空。 |
   
 表4ICommonMsg 
| **参数名称**  | **参数类型** |                                                                                                                                                                                                       **描述**                                                                                                                                                                                                        |
|---|---|---|
| Status    | number   | **参数解释：** OBS服务端返回的HTTP状态码。 **取值范围：** 状态码是一组从2xx（成功）到4xx或5xx（错误）的数字代码，状态码表示了请求响应的状态。完整的状态码列表请参见[状态码](https://support.huaweicloud.com/api-obs/obs_04_0114.html)。 |
| Code      | string   | **参数解释：** OBS服务端返回的错误码。                                                                                                                                                                                                                                                                                                                                    |
| Message   | string   | **参数解释：** OBS服务端返回的错误描述。                                                                                                                                                                                                                                                                                                                                  |
| HostId    | string   | **参数解释：** OBS服务端返回的请求服务端ID。                                                                                                                                                                                                                                                                                                                               |
| RequestId | string   | **参数解释：** OBS服务端返回的请求ID。                                                                                                                                                                                                                                                                                                                                  |
| Id2       | string   | **参数解释：** OBS服务端返回的请求ID2。                                                                                                                                                                                                                                                                                                                               |
| Indicator | string   | **参数解释：** OBS服务端返回的详细错误码。                                                                                                                                                                                                                                                                                                                                |
   
 表5GetBucketWebsiteOutput 
| **参数名称**              | **参数类型**                                                 | **描述**                                                                                                         |
|:---|:---|:---|
| RequestId             | string                                                   | **参数解释：** OBS服务端返回的请求ID。                                  |
| RedirectAllRequestsTo | [RedirectAllRequestTo] | **参数解释：** 所有请求重定向规则，详见[RedirectAllRequestTo]。 |
| IndexDocument         | [IndexDocument]         | **参数解释：** 默认页面配置，详见[IndexDocument]。             |
| ErrorDocument         | [ErrorDocument]        | **参数解释：** 错误页面配置，详见[ErrorDocument]。             |
| RoutingRules          | [RoutingRule]\[\]      | **参数解释：** 请求重定向规则列表，详见[RoutingRule]。           |
   
 表6IndexDocument 
| **参数名称** | **参数类型** | **是否必选**                 | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
|:---|:---|:---|:---|
| Suffix   | string   | 如果IndexDocument 设置则参数时必选 | **参数解释：** 该字段被追加在对文件夹的请求的末尾（例如：Suffix参数设置为"index.html"，请求的是"samplebucket/images/"，返回的数据将是"samplebucket"桶内名为"images/index.html"的对象的内容）。 **约束限制：** 该字段不能为空或者包含"/"字符。 **取值范围：** 无 **默认取值：** 无 |
   
 表7ErrorDocument 
| **参数名称** | **参数类型** | **是否必选**              | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|:---|
| Key      | string   | 如果ErrorDocument 设置时可选 | **参数解释：** 当4XX错误出现时使用的对象的名称。这个元素指定当错误出现时返回的页面。 **约束限制：** 无 **取值范围：** 长度大于0且不超过1024的字符串。 **默认取值：** 无 |
   
 表8RedirectAllRequestsTo 
| **参数名称** | **参数类型** | **描述**                                                              |
|:---|:---|:---|
| HostName | string   | **参数解释：** 重定向时使用的域名。如 www.example.com。 |
| Protocol | string   | **参数解释：** 重定向请求时使用的协议。               |
   
 表9RoutingRule 
| **参数名称**  | **参数类型**                                      | **描述**                                                                                                                                     |
|:---|:---|:---|
| Condition | [Condition]  | **参数解释：** 重定向规则生效需要满足的条件，详见[Condition]。  |
| Redirect  | [Redirect] | **参数解释：** 重定向请求时的具体信息，详见[Redirect]。                                       |
   
 表10Condition 
| **参数名称**                    | **参数类型** | **是否必选** | **描述**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|:---|:---|:---|:---|
| KeyPrefixEquals             | string   | 可选       | **参数解释：** 重定向生效时的对象名前缀。当向对象发送请求时，如果对象名前缀等于这个值，那么重定向生效。 例如：重定向ExamplePage.html对象的请求，KeyPrefixEquals设为ExamplePage.html。 **约束限制：** 与HttpErrorCodeReturnedEquals参数不可同时使用，两者二选一。 **取值范围：** 长度大于0且不超过1024的字符串。 **默认取值：** 无                                                                                                         |
| HttpErrorCodeReturnedEquals | string   | 可选       | **参数解释：** 重定向生效时的HTTP错误码。当发生错误时，如果错误码等于这个值，那么重定向生效。 例如：当返回的HTTP错误码为404时重定向到NotFound.html，可以将Condition中的HttpErrorCodeReturnedEquals设置为404，Redirect中的ReplaceKeyWith设置为NotFound.html。 **约束限制：** 与KeyPrefixEquals参数不可同时使用，两者二选一。 **取值范围：** 取值范围可参见[错误码](https://support.huaweicloud.com/api-obs/obs_04_0115.html)。 **默认取值：** 无 |
   
 表11Redirect 
| **参数名称**             | **参数类型** | **描述**                                                                                                                      |
|:---|:---|:---|
| Protocol             | string   | **参数解释：** 重定向请求时使用的协议。                                                                        |
| HostName             | string   | **参数解释：** 重定向请求时使用的域名。                                                                         |
| ReplaceKeyPrefixWith | string   | **参数解释：** 重定向请求时使用的对象名前缀。                                                                        |
| ReplaceKeyWith       | string   | **参数解释：** 重定向请求时使用的对象名。                                                                         |
| HttpRedirectCode     | string   | **参数解释：** 重定向请求时响应中的HTTP状态码，详见[状态码](https://support.huaweicloud.com/api-obs/obs_04_0114.html)。 |
   
#### 代码示例
您可以通过ObsClient.getBucketWebsite获取桶的托管配置。以下代码展示了如何获取名为examplebucket桶的网站配置。
```
// 引入obs库
// 使用npm安装
const ObsClient = require("esdk-obs-nodejs");
// 使用源码安装
// var ObsClient = require('./lib/obs');
// 创建ObsClient实例
const obsClient = new ObsClient({
  // 推荐通过环境变量获取AKSK，这里也可以使用其他外部引入方式传入，如果使用硬编码可能会存在泄露风险
  // 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // 【可选】如果使用临时AK/SK和SecurityToken访问OBS，同样建议您尽量避免使用硬编码，以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK，也可以使用其他外部引入方式传入。
  // security_token: process.env.SECURITY_TOKEN,
  // endpoint填写Bucket对应的Endpoint, 这里以华北-北京四为例，其他地区请按实际情况填写。
  server: "https://obs.cn-north-4.myhuaweicloud.com",
});
async function getBucketWebsite() {
  try {
    const params = {
      // 指定存储桶名称
      Bucket: "examplebucket",
    };
    // 获取桶的网站配置
    const result = await obsClient.getBucketWebsite(params);
    if (result.CommonMsg.Status <= 300) {
      console.log("Get bucket(%s)'s website configuration successful!", params.Bucket);
      console.log('RedirectAllRequestsTo:');
      console.log('HostName: %s', result.InterfaceResult.RedirectAllRequestsTo.HostName);
      console.log('Protocol: %s', result.InterfaceResult.RedirectAllRequestsTo.Protocol);
      console.log('IndexDocument[Suffix]: %s', result.InterfaceResult.IndexDocument.Suffix);
      console.log('ErrorDocument[Key]: %s', result.InterfaceResult.ErrorDocument.Key);
      console.log('RoutingRules:');
      for (let i = 0; i < result.InterfaceResult.RoutingRules; i++) {
        let routingRule = result.InterfaceResult.RoutingRules[i];
        let condition = routingRule.Condition;
        console.log("Condition[%d]-KeyPrefixEquals:%s, HttpErrorCodeReturnedEquals:%s",
          i, condition.KeyPrefixEquals, condition.HttpErrorCodeReturnedEquals
        );
        let redirect = routingRule.Redirect;
        console.log("Redirect[%d]-Protocol:%s, HostName:%s, ReplaceKeyPrefixWith:%s, HttpRedirectCode:%s",
          i, redirect.Protocol, redirect.HostName, redirect.ReplaceKeyPrefixWith, redirect.HttpRedirectCode
        );
      };
      return;
    };
    
    console.log("An ObsError was found, which means your request sent to OBS was rejected with an error response.");
    console.log("Status: %d", result.CommonMsg.Status);
    console.log("Code: %s", result.CommonMsg.Code);
    console.log("Message: %s", result.CommonMsg.Message);
    console.log("RequestId: %s", result.CommonMsg.RequestId);
  } catch (error) {
    console.log("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.");
    console.log(error);
  };
};
getBucketWebsite();
```
