0

I have to do request from node to Yii2 api. It doesn't throw any errors, but doesn't return anything either. When I do request to Yii2 api method directly in browser, value is returned. Here is my request in route in node:

router.get('', function (req, res) {

    var parameter = 20;

    request({
        url: 'http://**.**.**.***:8000/web/index.php?r=api/get-value',
        parameter: parameter,
        method: 'GET'
    }, function(error, response, body) {
        if(error || response.statusCode != 200)
            throw error;
        res.send(body);
    });
});

module.exports = router;

And here is method/endpoint in Yii2 controllers/apiController.php:

public function actionGetValue($inverterId) {
    return $inverterId * 2;
}

Any suggestions what could be wrong/missing?

Lina
  • 15
  • 9

2 Answers2

1

You can use the following

var http = require('http');
var client = http.createClient(8000, 'localhost');
var request = client.request('GET', '/web/index.php?r=api/get-value');
request.write("stuff");
request.end();
request.on("response", function (response) {
    // handle the response
});

Resource Link:

  1. Http request with node?
  2. Sending http request in node.js

or Another full example:

Get requests

Now we’ll set up a super simple test to make sure it’s working. If it’s not still running, run your simple Node server so that it’s listening on http://localhost:8000. In a separate file in the same directory as your http-request.js where your new module lives, add a file called test-http.js with the following contents:

// test-http.js

'use strict';

const
    request = require('./http-request'),
    config = {
        method: 'GET',
        hostname: 'localhost',
        path: '/',
        port: 8000
    };

request(config).then(res => {
    console.log('success');
    console.log(res);
}, err => {
    console.log('error');
    console.log(err);
});

This will import our module, run a request according to the configured options, and console log either the response, or an error if one is thrown. You can run that file by navigating to its directory in the command line, and typing the following:

$ node test-http.js

You should see the following response:

success
{ data: 'Cake, and grief counseling, will be available at the conclusion of the test.' }

Resource Link:

https://webcake.co/sending-http-requests-from-a-node-application/

SkyWalker
  • 28,384
  • 14
  • 74
  • 132
0

Okay, shame on me, I did not check, what's going on in public function beforeAction($action) in apiController.php - since request to endpoint getValue() is done from the "outside", it falls under a condition, that does not allow further actions and returns false - that's why response wasn't changing no matter what was done/set in getValue().

Lina
  • 15
  • 9