【问题标题】:Using Vercel for frontend and Heroku for api前端使用 Vercel,API 使用 Heroku
【发布时间】:2021-06-03 15:56:52
【问题描述】:

我想知道将我的 NextJS 应用程序部署在 Vercel 上并在 Heroku 上使用 Express api 来进行更繁重的 api 工作是否有意义。

我正在构建一个适用于图像处理的应用程序。 Vercel 的无服务器函数缺乏足够大的有效负载大小限制和函数超时时间,因此我很想将我的 api 移动到 Heroku 以绕过这一点。

这是一个合乎逻辑的解决方案,还是有人会提出更好的方法来绕过这些问题?还是让 Heroku 上的 Express api 仅用于这些繁重的工作是否更好?

【问题讨论】:

标签: express heroku next.js vercel


【解决方案1】:

我的回答是基于我的个人经验。我自己也在后端使用 Express.js API 运行 Next.js。我相信用 Vercel 托管您的前端并用 Heroku 托管您的自定义 API 也是一个合乎逻辑的提议,因为 Heroku 可以接受更大的有效负载并且专用于托管您的 API,这与 Vercel 仅服务于前端(和 Next .js 无服务器 API(如果可用)。

但是,您可能需要调整您的授权(如果有的话),使其适合您的用例。请记住,cookie 不能跨域发送。换句话说,从 Heroku 后端直接向 Next.js 前端发送一个 cookie 是不可能的,除非你做了几个变通方法,我现在都不知道。

我的解决方法是,您实际上可以使用 Next.js 无服务器 API作为代理将您的授权请求发送到您的自定义 API

例如,我将提供登录用户的方式,以展示如何使用 Next.js 的无服务器 API 和您的自定义 API 实现跨域 cookie。我将假设您将使用 JWT 作为对用户进行身份验证的方法。

// auth.js -> in your custom server

const userToken = await yourAuthorizationFunction();

// Send the token as an API response to your Next.js Serverless proxy.
res.status(200).json({
  status: 'success',
  token: userToken,
});

下面是从 Next.js API 获取 cookie 的方法。

// web/pages/myAuthentication.js -> your Next.js serverless API

import axios from 'axios';
import Cookies from 'cookies';

export default async (req, res) => {
  // 1. Receive the cookies here.
  const response = await axios.post(YOUR_ENDPOINT_TO_GET_COOKIES);  

  // 2. Set the JWT (or your token) to be used in the front-end.
  const cookies = new Cookies(req, res);
  cookies.set('jwt', response.data.token, {
    httpOnly: true,
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
    sameSite: 'lax',
  });

  // 3. Send success, cookie has been set.
  res.status(200).json({
    status: 'success',
  });
};

如果你想发出 POST 请求,你可以简单地从你的前端获取 cookie(如果你没有将 cookie 方法设置为 httpOnly 或者如果你使用 withCredentials 设置为 true),或者您可以再次调用您的代理 API,将所有数据传送到您的自定义服务器。

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 2017-08-06
    • 2015-11-28
    • 2022-09-28
    • 2023-01-03
    • 2021-12-01
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多