从另一个节点应用程序连接到Sails应用程序

时间:2018-09-09 00:34:32

标签: node.js http sails.js

我有一个有效的Sails应用程序,可以通过GUI登录。我现在正尝试通过单独的节点应用程序连接到它(登录)。该请求返回了403禁止访问。

app.js(独立的节点应用程序):

const querystring = require('querystring')
const http = require('http')

var email = "user@example.com"

var password = "abc123456"

const postData = querystring.stringify({
  'emailAddress': email,
  'password': password
});

var options = {
    host: "localhost",
    port: 1337,
    path: "/api/v1/entrance/login",
    method: "PUT",
    headers: {
      'Content-Type': 'text/plain'
    }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// write data to request body
req.write(postData);
req.end();

这正在记录:STATUS: 403 HEADERS: {"x-powered-by":"Sails <sailsjs.com>","content-type":"text/plain; charset=utf-8","content-length":"9","etag":"W/\"9-PatfYBLj4Um1qTm5zrukoLhNyPU\"", "set-cookie":["sails.sid=s%3AW7JFYuhhYcDuTGiETG3Chs7M9VLJ1AFJ.C%2FuKHdJFajHxM%2Bebxd29Zcw1EfjaK6fNUtnC8oSDoS4; Path=/; HttpOnly"],"date":"Sun, 09 Sep 2018 0 0:19:10 GMT","connection":"close"} BODY: Forbidde BODY: n No more data in response.

sails应用中的路线为'PUT /api/v1/entrance/login': { action: 'entrance/login' },

这是entrance/login操作(由sails生成器创建的默认控制器操作):

module.exports = {


  friendlyName: 'Login',


  description: 'Log in using the provided email and password combination.',


  extendedDescription:
`This action attempts to look up the user record in the database with the
specified email address.  Then, if such a user exists, it uses
bcrypt to compare the hashed password from the database with the provided
password attempt.`,


  inputs: {

    emailAddress: {
      description: 'The email to try in this attempt, e.g. "irl@example.com".',
      type: 'string',
      required: true
    },

    password: {
      description: 'The unencrypted password to try in this attempt, e.g. "passwordlol".',
      type: 'string',
      required: true
    },

    rememberMe: {
      description: 'Whether to extend the lifetime of the user\'s session.',
      extendedDescription:
`Note that this is NOT SUPPORTED when using virtual requests (e.g. sending
requests over WebSockets instead of HTTP).`,
      type: 'boolean'
    }

  },


  exits: {

    success: {
      description: 'The requesting user agent has been successfully logged in.',
      extendedDescription:
`Under the covers, this stores the id of the logged-in user in the session
as the \`userId\` key.  The next time this user agent sends a request, assuming
it includes a cookie (like a web browser), Sails will automatically make this
user id available as req.session.userId in the corresponding action.  (Also note
that, thanks to the included "custom" hook, when a relevant request is received
from a logged-in user, that user's entire record from the database will be fetched
and exposed as \`req.me\`.)`
    },

    badCombo: {
      description: `The provided email and password combination does not
      match any user in the database.`,
      responseType: 'unauthorized'
      // ^This uses the custom `unauthorized` response located in `api/responses/unauthorized.js`.
      // To customize the generic "unauthorized" response across this entire app, change that file
      // (see api/responses/unauthorized).
      //
      // To customize the response for _only this_ action, replace `responseType` with
      // something else.  For example, you might set `statusCode: 498` and change the
      // implementation below accordingly (see http://sailsjs.com/docs/concepts/controllers).
    }

  },


  fn: async function (inputs, exits) {

    // Look up by the email address.
    // (note that we lowercase it to ensure the lookup is always case-insensitive,
    // regardless of which database we're using)
    var userRecord = await User.findOne({
      emailAddress: inputs.emailAddress.toLowerCase(),
    });

    // If there was no matching user, respond thru the "badCombo" exit.
    if(!userRecord) {
      throw 'badCombo';
    }

    // If the password doesn't match, then also exit thru "badCombo".
    await sails.helpers.passwords.checkPassword(inputs.password, userRecord.password)
    .intercept('incorrect', 'badCombo');

    // If "Remember Me" was enabled, then keep the session alive for
    // a longer amount of time.  (This causes an updated "Set Cookie"
    // response header to be sent as the result of this request -- thus
    // we must be dealing with a traditional HTTP request in order for
    // this to work.)
    if (inputs.rememberMe) {
      if (this.req.isSocket) {
        sails.log.warn(
          'Received `rememberMe: true` from a virtual request, but it was ignored\n'+
          'because a browser\'s session cookie cannot be reset over sockets.\n'+
          'Please use a traditional HTTP request instead.'
        );
      } else {
        this.req.session.cookie.maxAge = sails.config.custom.rememberMeCookieMaxAge;
      }
    }//fi

    // Modify the active session instance.
    this.req.session.userId = userRecord.id;

    // Send success response (this is where the session actually gets persisted)
    return exits.success();

  }

};

我最终要完成的工作是能够在登录用户下的sails应用程序中创建数据库记录。因此,我尝试通过该应用程序登录,然后一旦登录,便使用已设置的api创建记录。

我如何成功登录Sails应用程序?

0 个答案:

没有答案