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

如何在Sails 1的Action 2中访问请求头?求Exit创建资料

Solving Action 2 Challenges in Sails.js 1.x

Hey there! I totally get the confusion with Action 2's structure at first—let's break down your two main issues and get you sorted out.


Accessing Request Headers (like Auth Tokens) in Action 2

While it's true that Action 2 centers around inputs and exits, you can absolutely access the request object and its headers through the Action's context (this). The this.req property gives you full access to the incoming request, including headers, params, and more.

Here's a quick example of how to grab an auth token from the request headers for validation:

module.exports = {
  inputs: {
    // Define your expected inputs here (if any)
  },
  exits: {
    invalidToken: {
      description: 'Missing or invalid authentication token.',
      responseType: 'unauthorized'
    },
    success: {
      description: 'Token validated successfully.'
    }
  },
  fn: async function (inputs, exits) {
    // Extract the Bearer token from the Authorization header
    const authHeader = this.req.headers.authorization;
    const token = authHeader ? authHeader.split(' ')[1] : null;

    if (!token) {
      return exits.invalidToken();
    }

    // Add your token validation logic here (e.g., verify JWT)
    // const decoded = await sails.helpers.jwt.verify(token);

    return exits.success({ message: 'Token is valid' });
  }
};

You can use this.req anywhere inside the fn function, or even in custom input validation functions if you need to check headers during input processing.


Creating Custom Exits in Action 2

Exits are defined in the exits object of your Action, and you can customize them to fit your app's needs. Each exit can include several optional properties to control behavior:

  • description: A human-readable explanation of when this exit is triggered
  • responseType: Maps to a pre-defined or custom response in Sails (e.g., 'badRequest', 'notFound', or a custom response you've created in config/responses/)
  • statusCode: Overrides the default HTTP status code for the response
  • fn: A custom function to handle the response logic directly (great for tailored outputs)

Example of Custom Exits

exits: {
  paymentRequired: {
    description: 'User needs to complete payment to access this resource.',
    statusCode: 402,
    responseType: 'paymentRequired' // Assumes you have a custom response for this
  },
  customSuccess: {
    fn: async function (data) {
      // Build a custom success response
      return this.res.status(200).json({
        success: true,
        payload: data,
        timestamp: new Date().toISOString()
      });
    }
  }
}

To trigger an exit, just return exits.[exitName](data), like:

// Trigger paymentRequired exit
return exits.paymentRequired();

// Trigger customSuccess with data
return exits.customSuccess({ user: currentUser });

Sails also includes built-in exits like success, badRequest, and serverError that you can use out of the box if you don't need custom behavior.


Glad you're planning to share your experience with other developers—that's what the community is all about! Let me know if you hit any other snags along the way.

内容的提问来源于stack exchange,提问作者Leonardo Freitas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:16:09