Próbuję zrobić małą stronę internetową, taką jak chorobler, dla mojego seedboxa: Chcę formularz wyszukiwania, który wyśle zapytanie do moich dostawców torrentów za pomocą tego interfejsu API: https:/ /github.com/JimmyLaurent/torrent-search-api
Udało mi się pobrać tekst z formularza, wykonać wywołania API i uzyskać wyniki wydrukowane w konsoli.
Ale kiedy próbuję przekazać je na stronę wyników, które wkrótce zostaną udostępnione, przekazuję tylko obietnice i nie do końca rozumiem zasadę obietnic.
Jeśli ktoś mógłby mi pomóc rozwiązać moje problemy, byłbym naprawdę bardzo wdzięczny lub przynajmniej dałby mi kilka wskazówek!
Oto mój kod złożony z kilku tutoriali ejs, nodejs dla początkujących:
const express = require('express');
const bodyParser = require('body-parser');
const app = express()
const TorrentSearchApi = require('torrent-search-api');
const tableify = require('tableify');
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')
async function search(query){ // Search for torrents using the api
var string = query.toLowerCase();
//console.log(string);
const torrents = await TorrentSearchApi.search(string,'All',20); // Search for legal linux distros
return(JSON.stringify(torrents));
}
app.get('/', function (req, res) {
res.render('index');
})
app.post('/', function (req, res) {
var rawTorrent = search(req.body.torrent);
var page = tableify(rawTorrent); //printing rawtorrent will only give me "promise"
res.render('results',page);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
1 odpowiedź
Twoja funkcja wyszukiwania używa async
/await
. Oznacza to, że funkcja wyszukiwania jest asynchroniczna i zwraca Promise
. Powinieneś poczekać na jego wynik (wiersz 23).
https://javascript.info/async-await
https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/async_function.
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const TorrentSearchApi = require('torrent-search-api')
const tableify = require('tableify')
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('view engine', 'ejs')
const search = async query => {
const loweredQuery = query.toLowerCase()
const torrents = await TorrentSearchApi.search(loweredQuery, 'All', 20)
return JSON.stringify(torrents)
}
app.get('/', (_, res) => res.render('index'))
app.post('/', async (req, res) => {
const torrents = await search(req.body.torrent) // Right here
const htmlTable = tableify(torrents)
res.render('results', htmlTable)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})