在Node.js中实现AJAX请求服务器端的正确方法 [英] Proper way to implement AJAX request server-side in Node.js

查看:56
本文介绍了在Node.js中实现AJAX请求服务器端的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个搜索引擎,在客户端POST搜索字符串后查询Twitter和Wiki API服务器端。当我仍然完全在客户端时,对Wiki API的AJAX请求看起来像:

I am building a search engine that queries the Twitter and Wiki APIs server-side after the client POSTs the search string. When I was still completely client-side the AJAX request to the Wiki API looked like:

$.ajax({
    url: 'https://en.wikipedia.org/w/api.php',
    data: {
        action: 'query',
        list: 'search',
        srsearch: searchString, // variable pulled from input
        format: 'json',
        //origin: 'https://www.mediawiki.org'
    },
    xhrFields: {
        withCredentials: true
    },
    dataType: 'jsonp' // will probably use 'json' now that I'm server-side
}).done( function ( data ) {
    searchParser(data);
});
... //searchParser() below

现在,我已经实现了一个节点。 js web应用程序从主页上的客户端表单POST获取搜索字符串( index.ejs )。然后,服务器将使用wiki和twitter搜索结果呈现结果页面( results.ejs )。已经使用 BoyCook的TwitterJSClient 处理Twitter API搜索。

Now, I have implemented a Node.js web app that takes the search string from a client-side form POST on the home page (index.ejs). The server will then render the results page (results.ejs) with the wiki and twitter search results. Twitter API search is already handled with BoyCook's TwitterJSClient.

我想知道从我的服务器执行此完全查询的最佳方法。我一直在环顾四周,找不到简洁的答案。有没有人对此有任何建议?

I would like to know the best way to perform this exact query from my server. I have been looking around and cannot find a succinct answer. Does anyone have any advice on this?

推荐答案

这是我基于乔纳森的回复:

Here is the solution I came to based on Jonathan's reply:

function wikiSearch () {

    var query = querystring.stringify({
        action: 'query',
        list: 'search',
        srsearch: searchString,
        srlimit: 10,
        srwhat: 'text',
        format: 'json'
    });
    var options = {
        hostname: 'en.wikipedia.org',
        path: '/w/api.php?' + query
    };

    var req = https.request(options, function(res) {

        if (!res) { 
            wikiData = "An error occured!";
            complete();
        };

        var body = '';
        console.log("statusCode: ", res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function(data) {
            body += data;
        });

        res.on('end', function() {
            wikiData = wikiDataParser( JSON.parse(body) );
            complete();
        });
    });

    req.end();
    req.on('error', function (err) {
        wikiData = "<h2>MediaWiki API is currently down.</h2>";
        complete();
    })

};
... // complete() is below

这改变了 wikiData 根据请求或响应变量。

This changes the wikiData variable according to the request or response.

这篇关于在Node.js中实现AJAX请求服务器端的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆