You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sails.js新手求助:控制器访问Action出现404错误

Troubleshooting 404 Errors in Sails.js Controller/View Setup

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

  1. Add a Route in config/routes.js
    Open your config/routes.js file and add a line that maps a URL path to your controller's list method. 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 /personal with a GET request, run the list function in PersonalController."

  2. Fix Your View Path (If You're Using res.view)
    You mentioned your view is in views/pages/personal.ejs, but your controller is calling res.view('personal'). Sails looks for views relative to the views directory, so you need to include the pages/ subfolder:

    module.exports = {
      list: function(req, res) {
        return res.view('pages/personal'); // Correct path to your view
      }
    };
    
  3. 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 with sails lift.

  4. 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 /personal should 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:10:45