【问题标题】:Why is my sapper backend code executed in my browser?为什么我的 sapper 后端代码在我的浏览器中执行?
【发布时间】:2020-07-09 13:43:50
【问题描述】:

所以,我正在尝试使用 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'”脚本标签中时被浏览器执行?

【问题讨论】:

    标签: javascript axios svelte sapper


    【解决方案1】:

    好吧,您的代码在浏览器中,因为&lt;script context="module"&gt; 在组件创建之前运行both on the server and on the client。此外,不应该有任何环境变量,因为它们可以被读取:

    不应引用任何 API 密钥或机密,否则将暴露于 客户

    所以我想你可以尝试Server Routes 或使用仅在客户端上运行的onMount 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2012-12-04
      相关资源
      最近更新 更多