You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 createServer request handler (so it runs on every incoming request)
  • Replace the hardcoded res.end text 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/await to 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/catch to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:43