【问题标题】:How to use MongoDB Stitch in Next.js如何在 Next.js 中使用 MongoDB Stitch
【发布时间】:2019-08-31 18:25:08
【问题描述】:

我计划使用 mongoDB Stitch。但它提供浏览器 SDK 和服务器 SDK 的方式不同。我尝试了他们两个,我得到了一些错误。我相信这是因为我的应用程序是同构的,因为我使用的是 Next.js。请指导我在这种情况下我该怎么办。

我在使用 mongodb-stitch-browser-sdk

时遇到类似 self is not defined 的错误

使用 mongodb-stitch-server-sdk 时出现Module not found: Can't resolve 'fs' 的一些问题。

请帮忙。我也在这个网站上看到了类似的问题,没有任何答案,here

【问题讨论】:

  • 您好,您能否在出现“未定义自我”错误的地方粘贴代码示例?
  • 对我来说同样的错误

标签: reactjs mongodb next.js isomorphic-javascript mongodb-stitch


【解决方案1】:

是的,因为 nextjs 构建了同构应用程序。所以尝试创建 webhook 并触发 mongodb 缝合 api,或者直接使用 webhook 中的服务。 这是通过stitch webhook注册使用的例子:

exports = function(payload) {
    const request = EJSON.parse(payload.body.text());
    const http = context.services.get("<app-title>");
    const owner = context.values.get("<username-of-the-app-owner>");
    const apiKey = context.values.get("<api-key>");

    return http.post({
        url: "https://stitch.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login",
        body: JSON.stringify({
            username: owner,
            apiKey: apiKey
        })
    }).then(response => EJSON.parse(response.body.text()).access_token).then(accessToken => {
        return http.post({
            url: "https://stitch.mongodb.com/api/admin/v3.0/groups/<group-id>/apps/<app-id>/users",
            headers: {
                Authorization: ["Bearer " + accessToken]
            },
            body: JSON.stringify({
                email: request.useremail,
                password: request.userpass
            })
        });
    });
};

这是使用 aws s3 服务的那个:

exports = function(payload) {
    //base64EncodedImage, bucket, fileName, fileType
    const body = EJSON.parse(payload.body.text());
    // Convert the base64 encoded image string to a BSON Binary object
    const binaryImageData = BSON.Binary.fromBase64(body.picture, 0);
    // Instantiate an S3 service client
    const s3Service = context.services.get('<aws-s3-service-title>').s3('<location>');
    // Put the object to S3
    return s3Service.PutObject({
        'Bucket': '<aws-bucket-title>',
        'Key': body.fileName,
        'ContentType': body.fileType,
        'Body': binaryImageData
    })
        .then(putObjectOutput => {
            // console.log(putObjectOutput);
            // putObjectOutput: {
            //   ETag: <string>, // The object's S3 entity tag
            // }
            return putObjectOutput;
        })
        .catch(console.error);
    // return body;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多