并表达为节点。js .request()

时间:2021-07-11 11:48:25

I'm trying to get a response from an outside url using the below code, but im having no luck. Can someone shed some light on what I'm doing wrong and give any pointers they think could be helpful.

我正在尝试用下面的代码从一个外部url获得响应,但是我没有运气。有人能不能解释一下我做错了什么,并给出他们认为有用的建议?

var express = require('express'),
              require('events');

var app = express.createServer();

app.request({
    host: "http://ws.audioscrobbler.com",
    port: 80,
    method: "GET",
    path: "/2.0/?method=artist.getsimilar&artist=bandname&api_key=b25b959554ed76058ac220b7b2e0a026"
}).on('response',function(response) {
    console.log(response);
});

app.listen(4000);

1 个解决方案

#1


3  

I don't know if you can. You could just use the built-in request function (see this:

我不知道你能不能。您可以使用内置的请求函数(请参见:

From the website:

从网站:

var http = require('http');

var options = {
    host: 'www.google.com',
    port: 80,
    path: '/upload',
    method: 'POST'
};

var req = http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
    });
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

It's pretty easy and you can still use it in your existing code...

这非常简单,您仍然可以在现有代码中使用它……

Sometimes frameworks don't have solutions for everything... the documentation is your friend.

有时候框架没有解决所有问题的解决方案……文件是你的朋友。

#1


3  

I don't know if you can. You could just use the built-in request function (see this:

我不知道你能不能。您可以使用内置的请求函数(请参见:

From the website:

从网站:

var http = require('http');

var options = {
    host: 'www.google.com',
    port: 80,
    path: '/upload',
    method: 'POST'
};

var req = http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
    });
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

It's pretty easy and you can still use it in your existing code...

这非常简单,您仍然可以在现有代码中使用它……

Sometimes frameworks don't have solutions for everything... the documentation is your friend.

有时候框架没有解决所有问题的解决方案……文件是你的朋友。