Node.js代码报SyntaxError: Unexpected end of input错误求助
Hey there, that SyntaxError: Unexpected end of input is almost always a sign you’ve got unclosed curly braces {} or parentheses () somewhere in your code. Let’s break down what’s going wrong and fix it:
The Root Cause
Looking at your code, you accidentally nested the app.delete("/articles") route inside the callback function of your app.post("/articles") route, and never closed the curly brace for the post route’s callback. This breaks the entire code structure, leading the parser to hit the end of the file before finding all required closing braces.
Corrected Code
Here’s the fixed version with proper indentation and closed braces:
const express = require("express"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const mongoose = require('mongoose'); const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); mongoose.set('useUnifiedTopology', true); mongoose.connect("mongodb://localhost:27017/restDB", { useNewUrlParser: true }); const articleSchema = { title: String, content: String } const Article = mongoose.model("Article", articleSchema); // GET all articles app.get("/articles", function(req, res) { Article.find(function(err, foundArticles) { if (!err) { res.send(foundArticles) } else { res.send(err) } }); }); // POST new article app.post("/articles", function(req, res) { const newArticle = Article({ title: req.body.title, content: req.body.content }); newArticle.save(function(err) { if (!err) { res.send("success") // Fixed typo here too! You had "succes" } else { res.send(err) } }); }); // <-- This closing brace was missing in your original code // DELETE all articles app.delete("/articles", function(req, res) { Article.deleteMany(function(err) { if (!err) { res.send("success") } else { res.send(err) } }); }); app.listen(3000, function() { console.log("Server started on port 3000"); });
Key Fixes I Made:
- Moved the
app.deleteroute outside of theapp.postcallback (Express routes should be top-level in your setup) - Added the missing closing curly brace
}for theapp.postroute’s callback function - Fixed a small typo: changed "succes" to "success" in the post route’s success response (not required to fix the error, but good practice)
- Added proper indentation to make the code structure easier to read and debug
Pro Tip for Future Debugging
Use an editor with built-in bracket matching (like VS Code) — it will highlight when you’re missing a closing brace/parenthesis. Keeping your code properly indented also makes it way easier to spot these kinds of syntax issues at a glance.
内容的提问来源于stack exchange,提问作者Shaikh Shoeb




