【发布时间】: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 我得到消息操作完成,没有任何错误。还有其他建议吗?
-
状态码是什么?