【问题标题】:trying to connect curl with express js试图将 curl 与 express js 连接起来
【发布时间】:2017-01-12 01:53:29
【问题描述】:

您好,我正在尝试使用 curl (php) 从我的站点连接到我制作的 rest api (node js-express-js)。除了 curl 的答案是空的之外,Everythink 似乎工作正常

来自 node-js 的服务器:

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());




var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();  

router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});


app.use('/api', router);

app.listen(port);
console.log('Listening on ' + port);

在我的网站上,我正在尝试使用 curl 检索 json:

<?php
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/"); // i removed the ip from my server for safety reasons

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string

    $output = curl_exec($ch);
print "output=";
print_r($ouput);
    // close curl resource to free up system resources
    curl_close($ch);
?>

注意:从邮递员那里发送一个获取请求,我收到了我想要的答案。我不知道出了什么问题。提前谢谢。

另外,curl 是一个阻塞函数.. 对吧?

两个“服务器”都在同一台服务器上。不知道是不是类似cross-server-origin of javascript之类的错误

【问题讨论】:

  • 你试过用简单的字符串回答吗?
  • @Lazyexpert 是的,我尝试了“res.send('test')”,但结果还是一样......什么都没有
  • 您可能会在curl_exec():if (curl_errno($ch)) { echo 'curl error: ' . curl_error($ch); } 之后检查 curl 错误。如果没有输出任何内容,请尝试使用 curl_getinfo($ch, CURLINFO_HTTP_CODE) 检查状态代码
  • @mscdex 我得到消息操作完成,没有任何错误。还有其他建议吗?
  • 状态码是什么?

标签: php node.js express curl


【解决方案1】:

没有通过 php 得到响应的原因 - print_r func 中的 var name 错误

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "xxx:8080/api/"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
print "output=";

print_r($output); // missed t in output

curl_close($ch);
?>

【讨论】:

  • 这个答案被标记为Low Quality 并且可以从解释中受益。以下是How do I write a good answer? 的一些指南。仅代码答案不被视为好的答案,并且可能会被否决和/或删除,因为它们对学习者社区不太有用。它只对你很明显。解释它的作用,以及它与现有答案(如果有的话)有何不同/更好。 From Review
  • 这个答案指出了一个错字。
  • 不要发布由错字类型问题引起的问题的答案,它们应该在 cmets 中被调用并标记,因为有一个特定的关闭标志 不可重现或由错字引起乙>。这些问题通常被否决、关闭和删除,因为它们对社区没有好处。
猜你喜欢
  • 2021-04-25
  • 2012-08-17
  • 2019-11-13
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 2022-01-20
  • 2017-09-18
  • 2021-12-17
相关资源
最近更新 更多