【问题标题】:How to use curl in Nodejs如何在 Nodejs 中使用 curl
【发布时间】:2019-04-29 22:48:49
【问题描述】:

我是NodeJS 的新手,我有一个名为“employe.html”的文件,我想在这个文件中使用curl,以便测试curl 我输入了以下代码,但它什么也没显示。

我可以在这个文件中使用curl 吗?如果是,那么我错在哪里?

这是我当前的代码:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
    req.write('hello');
  }
  else {
    console.log("Error "+response.statusCode)
    req.write('hellos');
  }
})

【问题讨论】:

  • 你有什么问题?你能详细说明一下吗?如果你得到html from google 为什么你需要不同的逻辑?
  • @narayansharma91:实际上,如果我使用上面的代码,那么现有数据不显示对我来说毫无用处,这就是为什么我问我哪里错了?我应该包含 jquery 还是 javascript 文件?因为我在 .html 文件中工作
  • 所以你的这个语句 `console.log(body) // 显示谷歌主页的 HTML。 ` 工作不正常?
  • @narayansharma91:是的,你是对的,为了测试我使用谷歌链接,我稍后会用我的 Api 链接替换以获取数据
  • 请添加更多信息。顺便说一句,你可以使用产卵来做到这一点。看看这个问题stackoverflow.com/questions/37229144/… spawning new thread 还有其他好处。例如您的主线程将保持干净的代码拆分等。

标签: node.js hapi


【解决方案1】:

尝试在 hapi 中为您提供静态 html 文件 employe.htmlpath='<domain name | localhost>/' 或您网站的根目录。您只需要根据您的目录结构修复 html 文件的路径。

const Hapi = require('hapi');
const Inert = require('inert');
const server = new Hapi.Server();

server.connection({port: 9200});


server.register(Inert, (err) => {

if (err) {
    throw err;
}

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply.file('/res/html/employe.html');
    }
});
server.route({
    path: "/res/{path*}",
    method: "GET",
    handler: {
        directory: {
            path: "./res",
            listing: false,
            index: false
        }
    }});


});
server.start();

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 2019-09-18
    • 2022-01-23
    • 2015-01-27
    • 2023-03-16
    • 2021-11-05
    • 2014-04-27
    • 2019-12-17
    • 2020-01-26
    相关资源
    最近更新 更多