Sails.js新手求助:控制器访问Action出现404错误
Hey there, fellow Sails.js learner! Let's break down why you're hitting that frustrating 404 error—this is a super common pitfall for new folks, so don't worry, we'll fix it.
The Root Cause: Missing Route Configuration
Sails.js doesn't automatically map your controller methods to URLs unless you explicitly set up routes (or use blueprint APIs, but let's stick to the basics first). Even if your controller and view are in the right places, without a route pointing to your list action, Sails has no idea where to send the request.
Step-by-Step Fixes
Add a Route in
config/routes.js
Open yourconfig/routes.jsfile and add a line that maps a URL path to your controller'slistmethod. For example:module.exports.routes = { // Map GET requests to /personal to PersonalController's list action 'GET /personal': 'PersonalController.list', };This tells Sails: "When someone visits
/personalwith a GET request, run thelistfunction inPersonalController."Fix Your View Path (If You're Using
res.view)
You mentioned your view is inviews/pages/personal.ejs, but your controller is callingres.view('personal'). Sails looks for views relative to theviewsdirectory, so you need to include thepages/subfolder:module.exports = { list: function(req, res) { return res.view('pages/personal'); // Correct path to your view } };Restart Your Sails Server
Any changes to routes or controller files require a server restart to take effect. Stop your running Sails instance (Ctrl+C) and restart it withsails lift.Test the JSON Response Again
Now that your route is set up, try your JSON controller code again:module.exports = { list: function(req, res) { return res.json({ todo: 'test' }); } };Visiting
/personalshould now show your JSON data instead of a 404.
Bonus: Check Blueprint APIs (Optional)
If you want Sails to auto-generate routes for your controller actions (like /personal/list for your list method), make sure blueprint actions are enabled in config/blueprints.js:
module.exports.blueprints = { actions: true, // This enables auto-routing for controller actions };
But for explicit control, manually setting routes is usually better when you're starting out.
内容的提问来源于stack exchange,提问作者chip

