向第三方 API 发送带有 GET 请求的标头

时间:2021-04-29 06:21:23

标签: javascript node.js node-fetch

我正在尝试构建一个小型的全栈应用程序,其中我的前端代码将只与我的后端交互,后端将调用第三方 API 来获取结果,然后用它做任何想做的事情。第三方 API对于任何请求,我都需要使用 Acceptapp_idapp_key 标头。

我可以使用 Postman 直接向我的第三方 API 发送 GET 请求并获取结果就好了,但是当我尝试通过我的 NodeJS API 发送 GET 请求时,我收到了 {{1 }} 反而 。为此,我使用了 status 403

我使用的 API 是 Oxford Dictionary API

这是我的 node-fetch 文件的代码

index.js

这是我的 require('dotenv').config(); const express = require('express'); const router = require('./routes/router'); const cors = require('cors'); const app = express(); const port = process.env.PORT || '5000'; const host = process.env.HOST || 'localhost'; app.use(cors()); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(router); app.listen(port, () => console.log(`server is up and running at http://${host}:${port} `)); 文件的代码。

router.js

以下是我收到的 const express = require('express') const fetch = require('node-fetch'); const router = express.Router(); const BASE_URL = process.env.BASE_URL; const fields = 'definitions'; router.get('/', (req, res) => { res.json({ status: "successfully connected !" }); }); router.post('/create', (req, res) => { console.log(req.body); console.log(req.body.word); const url = `${BASE_URL}entries/en-gb/${req.body.word}?fields=${fields}&strictMatch=true`; const newHeaders = { "Accept": "application/json", "app_id": process.env.APP_ID, "app_key": process.env.API_KEY } fetch(url, { method: 'GET', headers: { newHeaders } }) .then((results) => { console.log(results); }).then(results => { res.json(results); }).catch((err) => { console.log(err) }); }); module.exports = router; :-

results

请放心,Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: PassThrough { _readableState: [ReadableState], _events: [Object: null prototype], _eventsCount: 5, _maxListeners: undefined, _writableState: [WritableState], allowHalfOpen: true, [Symbol(kCapture)]: false, [Symbol(kTransformState)]: [Object] }, disturbed: false, error: null }, [Symbol(Response internals)]: { url: 'https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/swim?fields=definitions&strictMatch=true', status: 403, statusText: 'Forbidden', headers: Headers { [Symbol(map)]: [Object: null prototype] }, counter: 0 } } 都设置了准确的值。

我想成为 ale 附加 environment variables 并向第三方 API 发送 headers 请求并成功获取结果。此外,我希望能够将这些 GET 发送回我的客户。

我对我的代码有几个问题。

  1. 在快速路线内使用 results 是否正确?
  2. 如果是,为什么返回 fetch
  3. 如果不是,实现这一目标的正确方法是什么?
  4. status 403 是什么意思?

我是网络开发的新手,所以这个问题对于这里的一些老手来说可能看起来很愚蠢,但请帮助我。我已阅读以下资源,但没有一个对我有帮助:-

Accessing [Symbol(Response internals)] from JSON response

Node-Fetch API GET with Headers

How to fetch from third party API inside backend route?

编辑:

我使用了 headers: Headers { [Symbol(map)]: [Object: null prototype] },app-id 而不是 app-keyapp_id,我现在已经更正了,但问题还没有解决。

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,你有一个错字:

headers: { newHeaders } -- newHeaders 已经是一个对象,所以使用 headers: newHeaders