如何将HTML输入框文本存储到Node.js变量并结合API使用?
Got it! Let's walk through how to extend your existing Node.js server to handle form input from an HTML page, then use that data to call an external API. Here's a step-by-step implementation:
First, you'll need additional middleware to parse form data and a tool to make API calls. Run this command in your project folder:
npm install connect serve-static body-parser node-fetch
(Note: If you're using Node.js 18 or later, node-fetch is built-in, so you can skip installing it.)
Modify your server to handle form submissions and API calls. Here's the updated code:
var connect = require('connect'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); // For Node.js 18+, remove the line below and use the built-in fetch var fetch = require('node-fetch'); const app = connect(); // Parse URL-encoded form data from submissions app.use(bodyParser.urlencoded({ extended: true })); // Serve static HTML files from your WebDir folder app.use(serveStatic("WebDir")); // Handle form submission requests to /submit app.use('/submit', (req, res) => { if (req.method === 'POST') { // Extract the input value from the form (matches the input's "name" attribute) const userInput = req.body.userInput; // Call your target API with the input data fetch('https://your-api-endpoint-here.com', { method: 'POST', // Adjust method (GET/POST/PUT) based on your API's requirements headers: { 'Content-Type': 'application/json', // Update headers to match API expectations // Add any auth headers here if needed, e.g., 'Authorization': 'Bearer YOUR_TOKEN' }, body: JSON.stringify({ input: userInput }), // Send input data in the request body }) .then(apiResponse => apiResponse.json()) .then(apiData => { // Send the API's response back to the user as HTML res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(` <h2>Success!</h2> <p>Your input: ${userInput}</p> <h3>API Response:</h3> <pre>${JSON.stringify(apiData, null, 2)}</pre> `); }) .catch(error => { // Handle errors from the API call res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end(`Oops, something went wrong: ${error.message}`); }); } else { // Reject non-POST requests to this endpoint res.writeHead(405, { 'Allow': 'POST' }); res.end('Only POST requests are allowed here'); } }); app.listen(80, function(){ console.log('Server running on port 80...'); });
Inside your WebDir folder, create an index.html file with a simple input form:
<!DOCTYPE html> <html> <head> <title>Input Data to API</title> </head> <body> <h1>Enter Data to Send to API</h1> <form action="/submit" method="POST"> <label for="userInput">Your Input:</label> <input type="text" id="userInput" name="userInput" required placeholder="Type something..."> <button type="submit">Send to API</button> </form> </body> </html>
- Run your server with
node your-server-file.js - Open your browser and go to
http://localhost - Enter text in the input box and click "Send to API"
- You'll see your input and the API's response displayed on the page
Make sure to replace https://your-api-endpoint-here.com with your actual API URL, and adjust the request method, headers, and body format to match what the API expects.
内容的提问来源于stack exchange,提问作者Niklas

