You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Heroku中使用json-server?及部署方法咨询

Can I use json-server on a Heroku app? Yes, here's how to deploy it

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:
    web: npm start
    
    This tells Heroku how to start your application.
  • Create a .gitignore file 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 --tail to see what's going wrong.
  • Make sure your db.json is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:08:39