在Netlify Functions中使用Mongo Atlas API时的无效URL问题
问题与解决方案
问题说明
尝试从Mongo Atlas函数返回字符串,该功能在本地运行正常,但执行netlify deploy时提示无效URL。API URL和API密钥等.env变量已存储在Netlify服务器中,Mongo函数允许匿名认证和API密钥认证。曾尝试使用MongoDB推荐的请求头但未成功,也试过MongoClient包,但更倾向于使用Mongo函数端点。
Netlify函数代码
import axios from "axios" export async function handler(event, context) { const web = process.env.MONGO_ENDPOINT console.log(web) console.log("hi") try { const response = await axios.get(process.env.MONGO_ENDPOINT, { headers: { 'Content-Type':'application/json', 'Access-Control-Request-Headers':' *', 'api-key': process.env.KEY, } }) const data = response.data return { statusCode: 200, body: JSON.stringify({ msg: data[0].quote }) }; } catch (err) { console.log(err) // output to netlify function log return { statusCode: 500, body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err) } } }
Mongo Atlas函数代码
exports = function(arg){ const mongodb = context.services.get("Cluster0"); const db=mongodb.db("phi") const collection=db.collection("quotes"); const item = collection.aggregate([{ $sample: { size: 1 } }]) const quote =item return (quote); };
解决方案
核心修复点:在Netlify配置环境变量时,.env变量的值不需要添加引号。
内容的提问来源于stack exchange,提问作者Nolan Bruner
相关产品推荐
相关产品推荐

