Angular Todo应用提交报405、点击Done报500错误求助
Let's break down your two issues one by one and walk through fixes and checks:
1. 405 Method Not Allowed on POST Request
A 405 error means your backend isn't accepting POST requests at the http://todoapp.test/api endpoint. Here's what to check and fix:
Frontend Fix: Avoid Manual JSON Stringification
Your current code uses JSON.stringify(post) when sending the POST request, but Angular's HttpClient automatically serializes JavaScript objects to JSON. Manually stringifying can sometimes cause parsing issues on the backend. Update your createPost method:
createPost(input: HTMLInputElement) { const post: any = { name: input.value }; input.value = ''; // Remove JSON.stringify() - HttpClient handles this automatically this.http.post(this.url, post).subscribe({ next: (response) => { post.id = response.id; post.completed = false; // Set default completed state for new todos this.posts.splice(0, 0, post); }, error: (err) => console.error('Create failed:', err) // Add error logging for debugging }); }
Backend Checks:
- Confirm your backend has a POST route defined for
/apithat handles creating new todos. - Ensure CORS is configured correctly (if your frontend and backend run on different ports/domains) to allow POST requests.
- Verify the backend expects a JSON request body (not form data) and has middleware enabled to parse JSON (e.g., Laravel's
App\Http\Middleware\ConvertEmptyStringsToNullor Express'sexpress.json()). - If using CSRF protection (like in Laravel), make sure your Angular app includes the CSRF token in the request headers.
2. 500 Internal Server Error on Update (Done Button)
A 500 error points to a server-side issue, but the root cause here is a mismatched field name between your frontend and backend:
Frontend Fix: Align Field Names
In your HTML, you use post.completed to handle the todo's status:
[ngClass]="post.completed?'list-group-item list-group-item-success':'list-group-item'" {{ post.completed ? 'Done' : 'Not ready' }}
But in your updatePost method, you're sending a status field instead of completed:
this.http.put(this.url + '/' + post.id, JSON.stringify({ status: !post.status }))
Update the updatePost method to use completed (match what your HTML uses, and what your backend likely expects):
updatePost(post) { const updatedTodo = { completed: !post.completed }; this.http.put(`${this.url}/${post.id}`, updatedTodo).subscribe({ next: (response) => { post.completed = !post.completed; // Update the local todo's completed state }, error: (err) => console.error('Update failed:', err) // Add error logging }); }
Backend Checks:
- Confirm your
PUT /api/:idroute exists and correctly handles updating thecompletedfield of a todo. - Check for server-side errors (e.g., missing database columns, invalid query logic) by looking at your backend's error logs (this will tell you exactly what's causing the 500).
Bonus: Improve Error Handling
Adding error callbacks to your subscribe calls will give you more detailed error messages in the console, which makes debugging much easier (as shown in the code fixes above).
内容的提问来源于stack exchange,提问作者vargaadam

