【问题标题】:Pass data from React to Sails and return value将数据从 React 传递到 Sails 并返回值
【发布时间】:2021-06-09 14:06:35
【问题描述】:

在我的 React 应用程序中,我有三个字段:

firstNumber = 接受任何数字 >0

secondNumber = 接受任何数字 >0

operator = 接受 +,-,*,% 作为字符串

我想将它作为 POST 请求发送给 Sails,以便它可以进行计算。例如:2+3 返回 5。然后我会在 React 中显示返回值。

我已经写了 React 部分,我相信它是正确的。

  handleClick = (event) => {
    event.preventDefault()
    const inputField = {
      firstNumber: this.state.firstNumber,
      operator: this.state.operator, 
      secondNumber: this.state.secondNumber}
    const request = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ inputField })
    };
    fetch('http://localhost:1337/teste', request)
      .then(response => response.json())
      .then(data => this.setState({ total: data.valor}));
  }

在 Sails 中,我创建了一个控制器来处理这个问题。但是我找不到导入inputField并在函数中使用firstNumber、secondNumber和operator的数据的方法。

在 Sails.js 中需要执行哪些必要步骤?

【问题讨论】:

    标签: reactjs sails.js


    【解决方案1】:

    在 Sails 中,您可以在 api/controllers 文件夹中使用 Action2 控制器。

    
    module.exports = {
    
      friendlyName: 'Welcome user',
    
      description: 'Look up the specified user and welcome them, or redirect to a signup page if no user was found.',
    
      inputs: {
        userId: {
          description: 'The ID of the user to look up.',
          // By declaring a numeric example, Sails will automatically respond with `res.badRequest`
          // if the `userId` parameter is not a number.
          type: 'number',
          // By making the `userId` parameter required, Sails will automatically respond with
          // `res.badRequest` if it's left out.
          required: true
        }
      },
    
      exits: {
        success: {
          responseType: 'view',
          viewTemplatePath: 'pages/welcome'
        },
        notFound: {
          description: 'No user with the specified ID was found in the database.',
          responseType: 'notFound'
        }
      },
    
      fn: async function ({userId}) {
    
        // Look up the user whose ID was specified in the request.
        // Note that we don't have to validate that `userId` is a number;
        // the machine runner does this for us and returns `badRequest`
        // if validation fails.
        var user = await User.findOne({ id: userId });
    
        // If no user was found, respond "notFound" (like calling `res.notFound()`)
        if (!user) { throw 'notFound'; }
    
        // Display a personalized welcome view.
        return {
          name: user.name
        };
      }
    };
    
    

    因此,您可以在 fn: function(inputs) 中定义输入并处理它们,您可以在其中访问 inputs.firstNumber 和其他字段。

    来源:https://sailsjs.com/documentation/concepts/actions-and-controllers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-11
      • 2015-04-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多