首页 > 解决方案 > 为什么我的 sapper 后端代码在我的浏览器中执行?

问题描述

因此,我正在尝试使用 awios 从我的 sapper 服务器对 dockerized api 进行一些调用,并将结果传递给浏览器。我的电话由“call.js”文件提供。

我的“index.svelte”看起来像这样:

<script context="module">
  import * as calls from "./../../utils/calls.js";

  export async function preload({ params, query }) {
    try{
      
    let response = await calls.getStripePub();
    return { api_key: response.data.key };

    }catch(e){
      console.log(e, "error")
      this.error(500, "Oops, unexpected error there");
      
    }
  }
</script>

<script>
  import Payplace from "./../../components/payplace/Payplace.svelte";

  export let api_key;
</script>

<Payplace {api_key} />

我的 call.js 是:

import axios from "axios";

let backend = process.env.IP_BACK
let api_key = `${process.env.API_KEY_NAME}=${process.env.API_KEY}`

export async function getStripePub(){
    console.log(`http://${backend}/stripe/getkeypub/?${api_key}`);
    return await axios.get(`http://${backend}/stripe/getkeypub/?${api_key}`);
}

该代码在服务器端工作,但它也在我的浏览器中执行,显示

process is not defined

此外,我的浏览器下载的 index.js 文件包含

let backend = process.env.IP_BACK;
let api_key = `${process.env.API_KEY_NAME}=${process.env.API_KEY}`;

async function getStripePub(){
    console.log(`http://${backend}/stripe/getkeypub/?${api_key}`);
    return await axios$1.get(`http://${backend}/stripe/getkeypub/?${api_key}`);
}

为什么我的代码在“context='module'”脚本标签中被浏览器执行?

标签: javascriptaxiossveltesapper

解决方案


好吧,您的代码在浏览器中,因为在<script context="module">创建组件之前运行在服务器和客户端上。此外,不应该有任何环境变量,因为它们可以被读取:

不应该引用任何 API 密钥或秘密,这将暴露给客户端

所以我想你可以尝试服务器路由或使用仅在客户端上运行的onMount函数。


推荐阅读