如何将Node.js获取的Fortnite API数据输出到网页而非控制台?
How to Output Fortnite Duo Wins to the Web Page Instead of Console
Got it, let's fix this up for you. The core problem with your current code is that the Fortnite API logic runs only once when the server starts (inside the server.listen callback) and just dumps the result to the console. We need to tie that API data fetch to the HTTP request/response cycle so every time a browser hits your server, it fetches the stats and sends them back to the page.
Key Changes Needed:
- Move the Fortnite API fetch logic into the
createServerrequest handler (so it runs on every incoming request) - Replace the hardcoded
res.endtext with the actual stats data once it's retrieved - Add proper error handling to send meaningful messages to the browser if the API call fails
Modified Working Code:
/*server.js*/ const http = require('http'); const Fortnite = require("fortnite-api"); const hostname = '127.0.0.1'; const port = 3000; // Initialize the Fortnite API client once (outside request handler to reuse) const fortniteAPI = new Fortnite( [ "your-email", "your-password", "your-apikey", "your-apikeyserver" ], { debug: true } ); const server = http.createServer(async function(req, res) { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); try { // Login to Fortnite API (you might want to cache this session to avoid re-logging every request) await fortniteAPI.login(); // Fetch the BR stats for the target username const stats = await fortniteAPI.getStatsBR("target-username", "pc"); // Send the duo wins data back to the browser const duoWins = stats.group.duo.wins; res.end(`Hello browser, here's my data: Duo Wins: ${duoWins}`); } catch (err) { // Handle errors and send them to the browser instead of just logging console.error(err); res.statusCode = 500; res.end(`Error fetching Fortnite stats: ${err.message}`); } }); server.listen(port, hostname, function() { console.log(`Server running at http://${hostname}:${port}/`); });
Notes on Improvements:
- I used
async/awaitto make the asynchronous API calls cleaner (instead of nested.then()chains) - The Fortnite API client is initialized once outside the request handler to avoid recreating it every time
- Added error handling with
try/catchto gracefully handle login or stats fetch failures, and send an error response to the browser - You should replace the placeholder values (
your-email,your-password, etc.) with your actual Fortnite API credentials - For production, you'd want to cache the Fortnite API session token so you don't re-login on every request (since repeated logins might hit rate limits)
内容的提问来源于stack exchange,提问作者darrens
相关产品推荐
相关产品推荐

