reactjs - Running Express.js inside Next.js
问题描述
I'm trying to make Express running a neat way inside Next.js. As source of informations I used official documentation from Next.js website and their github repository about that topic
I succeed to make Express running, but I'm having bad development experience as every time I make changes inside files in my server directory, the server crashes and I've got this exception raised:
Error: Could not find a production build in the '/Users/******/******/nextjs-express/.next' directory. Try building your app with 'next build' before starting the production server. https://err.sh/vercel/next.js/production-start-no-build-id
****** personal path
So I've got to shut down the server, run npm run build
and then restart the server with npm run server
to apply changes without troubles. It's annoying. Here is my script in package.json
for npm run server
: nodemon --watch server server/index.js
- as you see I'm using nodemon
to watch every changes in my server directory.
1- So my first question is how can I apply changes to files inside my server directory without having to npm run build
every time I change something?
2- My second question is about data fetching on client side. Below a random auth component for instance.
export default function AuthComponent() {
const handleSignIn = async () => {
try {
const res = await fetch(
`http://localhost:${process.env.PORT}/api/auth/signin`,
{
method: 'GET',
}
)
console.log(res)
} catch (err) {
console.log(`Error: ${err}`)
}
}
return (
<div>
<button onClick={handleSignIn}>Sign in</button>
</div>
)
}
Inside fetch I've to hard code the server URL (port) like so (1) http://localhost:5000/api/auth/signin
(I established my server on port 5000) but I would like this server URL to be (2) /api/auth/signin
instead. If I leave the server URL like (2) I can't communicate with my backend as the URL remains localhost:3000
, the Next.js default one. Furthermore, taking into account that I've got env variables (in a .env.local
file) at the root of my project with one defining my server port (PORT=5000), I can't change (1) into http://localhost:${process.env.PORT}/api/auth/signin
because I can't access env variables from client side. So my second question is how to establish my server entry point as /api
(or /
or whatever) and not http://localhost:5000/api
(or whatever port) for client / browser?
Also you should know that I've written a proxy in my package.json like so "proxy": "http://127.0.0.1:5000"
but this does not work.
解决方案
推荐阅读
- html - Angular dom sanitize 无法正常工作
- sql - FULL OUTER JOIN 和类似功能
- google-apps-script - 谷歌电子表格 - 根据下拉选择删除单元格
- javascript - Vue-Router:为路由全局添加查询值
- php - phpdismod / phpenmod -s 参数
- java - Java中的抽象方法即使被覆盖也可以具有默认行为吗?
- python - Python - 覆盖现有文件的内容而不创建新文件
- c# - C#将对象作为参数发送到存储过程
- java - Selenium WebDriver:找到同一行上的两个值时,函数不会跳出循环
- node.js - 屏幕录制和网络摄像头(图片中的图片) - NodeJS