1

所以我想使用此处文档中的指南向我的弹性企业搜索应用程序发出搜索请求,我不想使用弹性节点 JS 客户端,但我想使用 axios 发出 http 请求。

这是我使用的代码

    const url = "https://XXXXXXX38ce49e5aff1aa238e6f9195.ent-search.asia-southeast1.gcp.elastic-cloud.com/api/as/v1/engines/events/search"
    const headers = {"Authorization": "Bearer search-qpz4bu5o7ubb8j31r15juyrh"}
    const jsonData = {
        query: "hello there"
    }


    try {

        const {data} = await axios.post(url,jsonData,headers)
        response.status(200).send(data)

    } catch (error) {
        console.log(error)
        response.status(500).send(error)

    }

但我总是收到这样的 401 错误:

{
    "message": "Request failed with status code 401",
    "name": "Error",
    "stack": "Error: Request failed with status code 401\n    at createError (/Users/xxx/Documents/elastic_jxxx/firebase_emulator/functions/node_modules/axios/lib/core/createError.js:16:15)\n    at settle (/Users/xxxx/Documents/elastic_jakarta_kumpul_muslim/firebase_emulator/functions/node_modules/axios/lib/core/settle.js:17:12)\n    at IncomingMessage.handleStreamEnd (/Users/xxxxx/Documents/elastic_xxxxx/firebase_emulator/functions/node_modules/axios/lib/adapters/http.js:244:11)\n    at IncomingMessage.emit (events.js:203:15)\n    at endReadableNT (_stream_readable.js:1145:12)\n    at process._tickCallback (internal/process/next_tick.js:63:19)",
    "config": {
        "url": "https://XXXXXXXa638ce49e5aff1aa238e6f9195.ent-search.asia-southeast1.gcp.elastic-cloud.com/api/as/v1/engines/events/search",
        "method": "post",
        "data": "{\"query\":\"hello there\"}",
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8",
            "User-Agent": "axios/0.20.0",
            "Content-Length": 28
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "Authorization": "Bearer search-qpz4bu5o7ubb8j31r15juyrh"
    }
}

我相信我已经输入了正确的搜索键,我可以像这样在邮递员中使用相同的 baseURL 和搜索键获得成功的响应

在此处输入图像描述

这里出了什么问题?

4

1 回答 1

2

headers需要在部件中作为命名对象config传递

所以试试这样:

const {data} = await axios.post(url, jsonData, { headers: headers })

或者更简洁:

const {data} = await axios.post(url, jsonData, { headers })

提示:Postman 能够在您点击Code. 因此,下次您不确定时,邮递员会为您提供帮助:

在此处输入图像描述

于 2020-09-28T11:20:35.600 回答