为什么我不能使用axios向我的 ElasticSearch 应用程序发出搜索请求?

ufj5ltwl  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(370)

所以我想使用这里的文档中的指南向我的 ElasticSearch 应用程序发出搜索请求,我不想使用弹性节点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)

    }

但我总是得到这样的错误:

{
    "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"
    }
}

我相信我已经把正确的搜索键,我可以得到成功的React使用相同的baseurl和搜索键在 Postman 这样

这里出了什么问题?

ve7v8dk2

ve7v8dk21#

这个 headers 需要作为中的命名对象传递 config 部分。
所以试着这样做:

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

或者更简洁地说:

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

提示:当您单击时,postman能够预先构造axios请求 Code . 所以下次你不确定的时候, Postman 会来帮忙:

相关问题