我正在尝试向URL发出GET请求,并使用node和express从那里获取图像作为响应。
这是我的代码:
var app = require('express')();
var http = require('http').Server(app);
app.get('http://tapas.clarin.com', (req, res) => {
res.sendFile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
该视图显示了Cannot GET /
。
如何才能使此请求正常工作以在我的视图中显示收到的图像?
HTML
<div id="tapas">
// I want to show the image from the response here!
</div>
<script src="./app.js"></script>
</body>
app.get()用于在服务器上创建GET API。你需要的是一个包,它可以帮助你对其他服务器进行API调用并从那里获取数据。
你可以使用request-promise
npm包让你的生活更轻松。
var rp = require('request-promise');
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
console.log('User has %d repos', repos.length);
})
.catch(function (err) {
// API call failed...
});
编辑:重新阅读您的问题后,您不需要进行GET API调用并在您的服务器上获取图像,然后再将其显示在您的网站上。您可以直接将URL传递给您的img标签,如下所示 -
<img src="https://url/image.png" alt="example">