如何修复Angular调用Express.js API时JSON.parse出现的意外令牌B错误?
That error means your Express server is trying to parse an incoming request body as JSON, but the first character is 'B'—which isn't valid JSON syntax. Let's break down how to debug and fix this:
First, Debug the Raw Request Body
The quickest way to figure out what's going wrong is to log the raw request body before Express tries to parse it. Add this middleware before your express.json() line in your Express code:
// Add this BEFORE app.use(express.json()) app.use((req, res, next) => { let rawBody = ''; req.on('data', chunk => rawBody += chunk.toString()); req.on('end', () => { console.log('Raw Request Body:', rawBody); next(); }); });
This will print exactly what your Angular app is sending. If you see something like "Bad Request" or a non-JSON string starting with 'B', that's the root cause.
Common Fixes Based on Debug Results
1. Ensure Angular Sends Valid JSON
Angular's HttpClient.post should automatically send JSON with the correct Content-Type: application/json header when you pass a plain object, but let's verify and enforce it:
First, check if your
blogobject is serializable. Runconsole.log(JSON.stringify(blog))in your Angular code—if this throws an error, yourbloghas non-serializable values (like circular references, functions, or custom objects that don't serialize cleanly). Fix this by convertingblogto a plain JS object (e.g., usingJSON.parse(JSON.stringify(blog))as a quick fix, or explicitly mapping properties).Explicitly set the Content-Type header in your Angular POST call to eliminate any ambiguity:
import { HttpHeaders } from '@angular/common/http'; public saveBlog(blog: any) { console.log('Blog object:', blog); console.log('Serialized JSON:', JSON.stringify(blog)); // Check if this is valid const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return this.http.post(`${host}/core/api/blogs`, blog, { headers }).toPromise(); }
2. Confirm Express Middleware Order
Your current Express middleware order looks correct, but double-check that express.json() runs before your route handler. The order matters—middleware runs top to bottom:
// Correct order: app.use(cors({ origin: true })); app.use(express.urlencoded({ extended: false })); app.use(express.json({ limit: '5mb' })); // Parses JSON body BEFORE routes app.use(errorHandler()); app.use("/core/api", blog ); // Routes come after body-parsing middleware
If express.json() were after your route, the route would receive the raw body and fail to parse it, but your current setup is right.
3. Check for Payload Size Issues
You've set a 5MB limit on JSON payloads, which is reasonable, but if your blog (e.g., with images) exceeds this, Express will truncate the body, leading to invalid JSON. If the raw body log shows a truncated string, increase the limit or optimize your payload.
Final Notes
Once you run the debug middleware, you'll know exactly what's causing the parse error. Most often, it's either an invalid JSON payload from Angular or a middleware ordering issue.
内容的提问来源于stack exchange,提问作者Ravi Rajput




