从nodeexpress应用程序向需要自己身份验证的第三方api发出请求的最佳方式是什么



我有一个node-express应用程序,它使用密钥斗篷身份验证来保护所有API端点。Express中间件已设置为进行身份验证,以确保来自前端的每个传入请求都具有适当的密钥斗篷令牌。我需要从我的节点应用程序向第三方后端API发出post请求,以向用户订阅使用不同身份验证方法的电子邮件服务,而我的中间件无法使用该方法。

向第三方API提出请求的最佳实践是什么?我正在考虑创建一个新的express实例,并使用专门用于该post请求的单独中间件。这样做可以吗?还是有更好的方法?

这是我的节点应用程序的简化版本。参见

index.js

import { authmware } from "./authmware";
import express from "express";
import { router } from "./router";
const app = express();
authmware(app);
router(app);
app.use((err, req, res, next) => {
logger.error(err.message);
const code = err.code ? err.code : 500;
const message = err.message ? err.message : "Internal Server Error";
res.status(code).json({ error: message, success: false });
});
export default app;

router.js

import express from "express";
import createProfile from "../../controllers/createProfile";

const router = express.Router();

router.post("/", createProfile);

export const router = (app) => {
app.use("/api/v1/createProfile", router);
};

controllers/createProfile.js

const createProfile = async (req, res) => {
// ... Do some stuff
// ** make request to a different api here ** 
await makeThirdPartyApiRequest();
}

我该如何发出使用不同身份验证风格的第三方api请求?

这是一个非常常见的用例。您可以在节点服务器中使用10个第三方API,所有这些API都具有不同的身份验证机制,而不考虑用于客户端请求的身份验证。

await makeThirdPartyApiRequest();
// http request to API
// attach proper auth headers (API key / jwt / basic auth / oAuth token). This will be based on the authentication method the API is offering.
}

根据您最近的评论更新:

API应该有一些关于如何使用用户密钥和密钥进行身份验证的文档。例如:Google API只要求您发送带有请求的API密钥https://cloud.google.com/api-keys/docs/overview

最新更新