Android开发Restful API搭建与上线步骤咨询(Node.js/Express/MongoDB)
Hey there! Let’s walk through this step by step—you already have Node.js basics under your belt, so we’ll build out your RESTful API with Express and MongoDB first, then get it deployed to Heroku so your Android app can hit it. No jargon overload, just actionable, straightforward steps.
1.1 Set Up Your Project
- First, create a new folder for your API, open it in your terminal, and run these commands to initialize the project and install dependencies:
npm init -y npm install express mongoose cors dotenvexpress: The lightweight framework we’ll use to build the API structuremongoose: An ODM (Object-Document Mapper) that simplifies working with MongoDBcors: Lets your Android app (running on a different device/port) access the API without cross-origin errorsdotenv: Keeps sensitive info (like your MongoDB password) out of your public code
1.2 Connect to MongoDB
- Create a
.envfile in your project root, and add your MongoDB connection string (you can get this from MongoDB Atlas if using a cloud database, or usemongodb://localhost:27017/your-db-namefor local MongoDB):MONGO_URI=mongodb+srv://<your-username>:<your-password>@cluster0.mongodb.net/your-db-name?retryWrites=true&w=majority PORT=5000 - Create a
server.jsfile (the main entry point for your API) and add this code to connect to MongoDB and start the server:const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); require('dotenv').config(); const app = express(); // Middleware to handle requests app.use(cors()); app.use(express.json()); // Parse JSON data from requests // Connect to MongoDB mongoose.connect(process.env.MONGO_URI) .then(() => console.log('MongoDB connected successfully!')) .catch(err => console.error('MongoDB connection error:', err)); // Start the server const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
1.3 Create a Model & CRUD Routes
Let’s use a simple "Notes" API as an example (adjust this to match your app’s needs):
- Create a
models/Note.jsfile to define your data structure:const mongoose = require('mongoose'); const noteSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Note', noteSchema); - Create a
routes/notes.jsfile to handle CRUD operations:const express = require('express'); const router = express.Router(); const Note = require('../models/Note'); // Get all notes router.get('/', async (req, res) => { try { const notes = await Note.find(); res.json(notes); } catch (err) { res.status(500).json({ message: err.message }); } }); // Create a new note router.post('/', async (req, res) => { const note = new Note({ title: req.body.title, content: req.body.content }); try { const newNote = await note.save(); res.status(201).json(newNote); } catch (err) { res.status(400).json({ message: err.message }); } }); // Get a single note by ID router.get('/:id', getNote, (req, res) => { res.json(res.note); }); // Update a note router.patch('/:id', getNote, async (req, res) => { if (req.body.title) res.note.title = req.body.title; if (req.body.content) res.note.content = req.body.content; try { const updatedNote = await res.note.save(); res.json(updatedNote); } catch (err) { res.status(400).json({ message: err.message }); } }); // Delete a note router.delete('/:id', getNote, async (req, res) => { try { await res.note.deleteOne(); res.json({ message: 'Note deleted successfully' }); } catch (err) { res.status(500).json({ message: err.message }); } }); // Reusable middleware to fetch a note by ID async function getNote(req, res, next) { let note; try { note = await Note.findById(req.params.id); if (!note) return res.status(404).json({ message: 'Note not found' }); } catch (err) { return res.status(500).json({ message: err.message }); } res.note = note; next(); } module.exports = router; - Link this route to your
server.jsby adding these lines:const notesRouter = require('./routes/notes'); app.use('/api/notes', notesRouter);
1.4 Test Your Local API
- Run
node server.jsto start the server - Use tools like Postman or curl to test the endpoints:
GET http://localhost:5000/api/notesto fetch all notesPOST http://localhost:5000/api/noteswith a JSON body ({"title":"Test Note","content":"Hello from my API!"}) to create a note
First, quick overview: Heroku is a Platform-as-a-Service (PaaS) that lets you host and run your API without managing physical servers. It handles scaling, hosting, and deployment for you—perfect for your Android app’s backend.
2.1 Prepare Your Project for Deployment
- Update your
package.jsonto include astartscript (Heroku uses this to run your app):"scripts": { "start": "node server.js", "dev": "nodemon server.js" // Optional, for local development } - Create a
.gitignorefile to exclude files you don’t want to push to Heroku:node_modules/ .env - Initialize a Git repository (if you haven’t already):
git init git add . git commit -m "Initial API setup"
2.2 Set Up Heroku
- Install the Heroku CLI (command-line tool) on your computer
- Log in to Heroku via the terminal:
heroku login - Create a new Heroku app (replace
your-api-namewith something unique):heroku create your-api-name
2.3 Add Environment Variables to Heroku
You can’t push your .env file to Heroku, so we’ll set those variables directly in Heroku’s system:
- Run this command to add your MongoDB connection string:
heroku config:set MONGO_URI=mongodb+srv://<your-username>:<your-password>@cluster0.mongodb.net/your-db-name?retryWrites=true&w=majority
2.4 Deploy Your API
- Push your code to Heroku’s Git repository:
git push heroku main - Once deployment finishes, make sure your app is running:
heroku ps:scale web=1 - Get your API’s public URL (this is what you’ll use in your Android app):
Your base URL will look likeheroku openhttps://your-api-name.herokuapp.com, so your notes endpoint becomeshttps://your-api-name.herokuapp.com/api/notes
2.5 Test the Deployed API
Use Postman or your Android app to send requests to the Heroku URL—everything should work exactly like it did locally!
内容的提问来源于stack exchange,提问作者Asem Abd-elnaser

