node.js + wordpress 返回帖子数据

问题描述 投票:0回答:2

我正在开发一个node.js服务器来获取外部api数据,然后使用我的客户端从我的节点服务器获取数据,而不是调用api站点。

我正在使用express、axios、https

我已经为我的node.js 创建了端点

工作示例之一: 常量 URL3 =

https://strainapi.evanbusse.com/${STAIN_API}/strains/search/all
;


var myDta = https.get(URL3, (resp) => {
    let i = 1;
    let data = '';

    resp.on('data', (chunk) => {
        data += chunk;
    });
    resp.on('end', () => {

        strains = JSON.parse(data)
        return strains
    });
}).on("error", (err) => {
    console.log("Error: " + err.message);
});

var strains = myDta


app.get("/orders", (req, res, next) => {
    res.json(myDta);
})

并且端点在 Node.js 中工作正常。

现在,为了获取我正在做的 WordPress 帖子:

const URL1='https://example.com/wp-json/wp/v2/posts'

var postData = axios.get(URL1)
    .then(response => response.data)
    .then((data) => {
        pushPost = [];
        k = data[0]
        pushPost.push(k)
        console.log('my data ', pushPost) //This gives me the post data
        return pushPost
    })

var postDataRes = postData

console.log('this pushpost ', postDataRes) 
//this gives me an empty array

app.get("/posts", (req, res, next) => {
    res.json(postDataRes)
})

但是我正在获取空对象,但在控制台中我可以使用以下方法获取我想要的帖子:

console.log('my data ', pushPost)

无法理解为什么我无法将发布数据推送到我的node.js 服务器中的端点。

node.js wordpress
2个回答
1
投票

您需要阅读并练习 JavaScript Promise/异步执行。您定义并提供给 .then() 的函数将在 after

console.log('this pushpost ', postDataRes)
执行,您从 Promise 获得的任何数据只能在其 .then() 函数内部访问。

此外,您可能希望在路由内进行数据获取,或者只会在加载expressjs服务器时发生一次。

const URL1='https://example.com/wp-json/wp/v2/posts'

app.get("/posts", (req, res, next) => {
    axios.get(URL1)
        .then(response => response.data)
        .then((data) => {
            const pushPost = [];
            k = data[0]
            pushPost.push(k)
            console.log('my data ', pushPost) //This gives me the post data

            res.json(pushPost)
        })

})

0
投票

我做相反的事情 我想从 WordPress 中的 node.js 接收数据 问题是我收到这个错误 WP_Error 对象 ( [错误] => 数组 ( [http_request_failed] => 数组 ( [0] => cURL 错误 7: 无法连接到本地主机端口 3040: 连接被拒绝 )

     )

 [error_data] => Array
     (
     )

 [additional_data:protected] => Array
     (
     )

) 虽然当我在浏览器中阅读时我得到了正确的答案 仅从 WP 中的代码我再次收到错误 这是 WordPress 中的代码: 函数 get_data_from_node() {

$protocol = is_SSL() ? 'https://' : 'http://';
$url =  "{$protocol}localhost:3040/data";
$response = wp_remote_get($url);
print_r($response);

回显“fvfvfvfvfv”; 如果 (is_wp_error($response)) { return new WP_Error('node_request_failed', '从 Node.js 服务器获取数据时出错。', array('status' => 500)); }

© www.soinside.com 2019 - 2024. All rights reserved.