能否在Heroku中使用json-server?及部署方法咨询
Absolutely—deploying json-server to Heroku is totally doable, and it's a great way to host a mock REST API for your projects. Let's walk through the full process step by step:
Step 1: Set up your local project
First, create a new folder for your project and initialize it with npm:
mkdir my-json-api && cd my-json-api npm init -y
Next, install json-server as a dependency:
npm install json-server
Step 2: Create your data file
Make a db.json file in your project root—this is where your mock data lives. Here's a simple example:
{ "posts": [ { "id": 1, "title": "Hello World", "content": "First post!" } ], "comments": [ { "id": 1, "postId": 1, "text": "Great post!" } ] }
Step 3: Configure your start script
Open your package.json file and update the scripts section to include a start command for json-server:
"scripts": { "start": "json-server --watch db.json --port $PORT" }
Note: We use $PORT here because Heroku dynamically assigns a port to your app—you can't hardcode a specific port like 3000.
Step 4: Add required Heroku files
- Create a
Procfile(no file extension) in your project root with this line:
This tells Heroku how to start your application.web: npm start - Create a
.gitignorefile to exclude unnecessary files from being pushed to Heroku:node_modules/ .env
Step 5: Deploy to Heroku
First, initialize a git repository if you haven't already:
git init git add . git commit -m "Initial commit: json-server setup"
Then, use the Heroku CLI to create your app and deploy:
# Log in to Heroku (if you haven't already) heroku login # Create a new Heroku app (Heroku will generate a random name, or you can specify one with --name) heroku create # Push your code to Heroku git push heroku main
Step 6: Test your API
Once the deployment finishes, open your app with:
heroku open
You'll see the json-server interface, and you can access your endpoints like https://your-heroku-app-name.herokuapp.com/posts to get your mock data.
Troubleshooting tips
- If your app crashes, check the logs with
heroku logs --tailto see what's going wrong. - Make sure your
db.jsonis valid JSON—invalid syntax will cause the server to fail. - If you need to update your data, just modify
db.json, commit the change, and push to Heroku again.
内容的提问来源于stack exchange,提问作者Irakli Sartania

