1

我在 php 中有一个较旧的系统,因此,我正在使用带有 Express 框架的 Node.js 编写一个新系统,在 Node.js 站点的某个地方我需要登录到 php 站点(这些站点使用相同的凭据)。

基本上我在 mi 视图(在 Express 中)的某个地方有一个按钮,当按下它时,应该从某个地方获取一些用户凭据,使用此凭据(没有任何表单)登录到 php 站点并重定向到已经登录的 php 系统在浏览器上。

我正在尝试遵循这个答案

因此,这是在按下按钮时执行的代码。

app.post('/loginphp', function(req, res) {

  var data = request.post(
    'http://somesite.somedomain.com/Users/login', {
      form:{
       'data[User][email]': 'someuser@somedomain.com',
       'data[User][pass]' : 'somepassword'
      }
    }, function(error, response, body) {

      var sessionCookie = response.headers['set-cookie'][response.headers['set-cookie'].length - 1];
      sessionCookie = sessionCookie.split(';');
      sessionCookie = sessionCookie[0];

      // trying with this way  the same results

      /*
         res.set({'Cookie' : sessionCookie}).
           redirect('http://somesite.somedomain.com/Users');
      */

      // and same results too in this one

      /*
         res.setHeader('Cookie', sessionCookie).
           redirect('http://somesite.somedomain.com/Users');
      */


      res.header('Cookie', sessionCookie)
         .redirect('http://somesite.somedomain.com/Users');

      //the output shows the cookie is saved just fine on headers

      /*console.log(res.header());*/


      // Doing this!!! -> WORKS!! , but i need be on the browser not here.

      /*
       request.get('http://somesite.somedomain.com/Users', {
          headers: {"Cookie" : sessionCookie},
        }, function (error, response, body) {
          if(response.statusCode == 200) {
           console.log(body);
          }
       });
      */

    });
});

取消注释最后一段注释的代码(来自 request.get),我可以看到这很好,并且正在打印登录网站用户主页的 HTML(正文),但是当我尝试在标题中设置 Cookie 并重定向时到该站点以在浏览器上进行登录,这不起作用

可以通过这种方式做到这一点吗?

我错过了什么?

提前致谢。

4

1 回答 1

1

@Gonzalo 您仍然可以访问运行 cakephp 应用程序的(服务器/代码)吗?

您需要添加一个跨域标头以允许您的 node.js (express) 应用程序向 cakephp 应用程序/网站发出 POST 请求。

例如:

<?php
 header("Access-Control-Allow-Origin: *");

或特定于 CakePHP:

$this->response->header('Access-Control-Allow-Origin', '*');

然后你可以通过运行来测试它:

curl -H "Content-Type: application/json" -dv "{'data[User][email]':'someuser@somedomain.com','data[User][pass]' : 'somepassword'}" http://somesite.somedomain.com/Users/login

确认标题包含类似于以下内容的条目:

Access-Control-Allow-Origin: *

这将允许您从 Node(使用请求)和客户端应用程序中访问 PHP 应用程序。

更多信息:

如果您仍然无法向 CakePHP 应用程序发送 POST 请求,请告诉我(在评论中)。

于 2014-08-06T15:19:06.300 回答