我是否必须使用ngrok暴露前端和后端,以使CRUD操作正常工作? [英] Do I have to expose front and back ends with ngrok for MERN stack for CRUD ops to work?

查看:77
本文介绍了我是否必须使用ngrok暴露前端和后端,以使CRUD操作正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在本地计算机上开发MERN应用程序.

I am developing a MERN app on my local machine.

前端位于localhost:3000

The front end is on localhost:3000

后端位于localhost:3003

The back end is on localhost:3003

我的前端代码中有一个请求,如下所示:

I have in my front end code a request, like so:

axios.get('localhost:3000/comments',params)

现在,我使用ngrok公开应用程序,如下所示:

Now, I use ngrok to expose the app, like so:

ngrok start front_end back_end

和我的.yml配置文件如下:

and my .yml config file looks like:

tunnels:
    front_end:
        proto: http
        addr: 3000
        subdomain: fakedomaintest
    back_end:
        proto: http
        addr: 3003
        subdomain: fakedomaintestback

我的问题是,我是否必须以其他方式暴露后端,还是我将堆栈拆分错误?

My question was, do I have to expose the back end in a different way, or am I splitting the stack wrong?

当我公开localhost:3000和localhost:3003时,我在前端代码中编辑CRUD行以匹配ngrok URL,如下所示:

axios.get('fakedomaintestback.ngrok.io/comments',参数)

,并且在访问 fakedomaintest.ngrok.io 后,它就可以使用....

但是,有没有一种更简便的方法,使我不必每次想将ngrok用于远程原型时都在前端编辑CRUD行?

But is there an easier way wherein I do not have to edit the CRUD lines on the front end everytime I want to use ngrok for a remote prototype?

我在这里想念什么?

推荐答案

如果您的应用程序在 localhost:3003 上运行,则您的axios调用应为 axios.get('localhost:3003/comments',params)

If your app is running at localhost:3003 then your axios call should be axios.get('localhost:3003/comments', params)

要解决网址切换:

您可以使用 dotenv 为您的应用程序设置环境变量.

You could use dotenv to set up environment variables for your application.

https://www.npmjs.com/package/dotenv

它是如何工作的,您将在react应用程序的根文件夹中创建一个 .env 文件,其中包含以下内容:

How it would work is you would create a .env file in the root folder of your react application containing the following:

BACKEND_HOST=localhost:3003

然后,您可以在代码中将所有网络调用更改为以下内容:

Then in your code you could change all your network calls to the following:

axios.get(`${process.env.BACKEND_HOST}/comments`, params)

要切换为使用ngrok时,只需更改 .env 文件中的值即可.

When you want to switch to using ngrok, you can simply change the value in the .env file.

如果您恰好正在使用Create React App,则已经支持 .env 文件,但是您必须在所有变量前加上 REACT_APP 前缀,因此 BACKEND_HOST 将变为 REACT_APP_BACKEND_HOST

If you happen to be using Create React App, .env files will already be supported, but you'll have to prefix all your variables with REACT_APP, so BACKEND_HOST would become REACT_APP_BACKEND_HOST

这篇关于我是否必须使用ngrok暴露前端和后端,以使CRUD操作正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆