【问题标题】:Http request from Node (Express) to Yii2 api endpoint从 Node (Express) 到 Yii2 api 端点的 Http 请求
【发布时间】:2017-08-15 10:35:59
【问题描述】:

我必须从节点请求 Yii2 api。 它不会抛出任何错误,但也不会返回任何内容。 当我直接在浏览器中向 Yii2 api 方法请求时,返回值。这是我在节点路由中的请求:

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;

这里是 Yii2 控制器/apiController.php 中的方法/端点:

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

有什么建议可能是错误/遗漏的吗?

【问题讨论】:

    标签: node.js rest express yii2 request


    【解决方案1】:

    你可以使用下面的

    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
    });
    

    资源链接:

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

    或另一个完整的例子:

    获取请求

    现在我们将设置一个超级简单的测试来确保它正常工作。如果它还没有运行,请运行您的简单节点服务器,以便它正在侦听http://localhost:8000。在与新模块所在的 http-request.js 相同的目录中的单独文件中,添加一个名为 test-http.js 的文件,其内容如下:

    // 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);
    });
    

    这将导入我们的模块,根据配置的选项运行请求,并在控制台记录响应,或者如果抛出错误则记录错误。您可以通过在命令行中导航到其目录并键入以下内容来运行该文件:

    $ node test-http.js

    您应该会看到以下响应:

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

    资源链接:

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

    【讨论】:

      【解决方案2】:

      好吧,真丢脸,我没有检查,apiController.php 中的 public function beforeAction($action) 发生了什么 - 因为对端点 getValue() 的请求是从“外部”完成的",它属于不允许进一步操作并返回 false 的条件 - 这就是为什么无论在 getValue() 中完成/设置什么,响应都不会改变。

      【讨论】:

        猜你喜欢
        • 2015-12-16
        • 2015-07-05
        • 2019-09-11
        • 1970-01-01
        • 2017-10-06
        • 2016-08-09
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        相关资源
        最近更新 更多