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

如何通过表单传递值至JS文件并执行NodeJS逻辑

Hey Rodrigo, let's break this down step by step since you're already halfway there with your Express setup! The key here is to turn your inndetails.js into a reusable module, then call its method directly from your route handler when the form is submitted.

Step 1: Refactor inndetails.js to expose its functionality

First, we need to make the sdk.getIinDetails method callable from other files. Wrap it in an exported function so your route can import and use it:

// inndetails.js
// Assume your SDK is already initialized here
const sdk = require('your-sdk-package'); // Replace with your actual SDK import

// Export a reusable function that takes MerchantID and Valor
async function fetchIinDetails(merchantId, valor) {
  try {
    // Call the SDK method with your form data
    const details = await sdk.getIinDetails({
      MerchantID: merchantId,
      Valor: valor
      // Add any other required parameters your SDK expects here
    });
    return details;
  } catch (error) {
    console.error('Failed to fetch IIN details:', error);
    throw error; // Pass the error up to the route handler to handle
  }
}

module.exports = { fetchIinDetails };

Note: If your SDK uses callbacks instead of Promises, wrap it in a Promise like this:

function fetchIinDetails(merchantId, valor) {
  return new Promise((resolve, reject) => {
    sdk.getIinDetails(
      { MerchantID: merchantId, Valor: valor },
      (error, result) => {
        if (error) reject(error);
        else resolve(result);
      }
    );
  });
}

Step 2: Update your route to call the inndetails.js function

In your routes/index.js, import the exported function and use it in your POST handler before rendering teste2.ejs:

// routes/index.js
const express = require('express');
const router = express.Router();
const { fetchIinDetails } = require('../inndetails'); // Import the function

// Your existing GET route to render the form
router.get('/teste', (req, res) => {
  res.render('teste');
});

// Updated POST route to handle form submission + SDK call
router.post('/teste', async (req, res) => {
  try {
    // Extract form data from req.body (thanks to Body Parser!)
    const { MerchantID, Valor } = req.body;

    // Call the SDK method from inndetails.js
    const iinDetails = await fetchIinDetails(MerchantID, Valor);

    // Pass the original form data AND SDK results to teste2.ejs
    res.render('teste2', {
      MerchantID,
      Valor,
      iinDetails,
      error: null
    });
  } catch (error) {
    // Handle errors gracefully by passing an error message to the view
    res.render('teste2', {
      MerchantID: req.body.MerchantID,
      Valor: req.body.Valor,
      iinDetails: null,
      error: 'Oops! Failed to retrieve IIN details. Please try again.'
    });
  }
});

module.exports = router;

Step 3: Double-check your form and middleware setup

Make sure your teste.ejs form is pointing to the correct POST route and uses the right field names:

<!-- views/teste.ejs -->
<form method="POST" action="/teste">
  <div>
    <label>Merchant ID:</label>
    <input type="text" name="MerchantID" required>
  </div>
  <div>
    <label>Valor:</label>
    <input type="number" name="Valor" required>
  </div>
  <button type="submit">Submit</button>
</form>

And confirm Body Parser is properly configured in your main app.js file:

// app.js
const express = require('express');
const bodyParser = require('body-parser');
const indexRouter = require('./routes/index');

const app = express();

// Configure Body Parser to parse form data
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Set up EJS as your view engine
app.set('view engine', 'ejs');
app.set('views', './views');

// Mount your routes
app.use('/', indexRouter);

app.listen(3000, () => console.log('Server running on port 3000'));

Now when you submit the form, your route will grab the data, pass it to inndetails.js to run the SDK method, then render teste2.ejs with both the original form values and the SDK results (or an error message if something goes wrong).

内容的提问来源于stack exchange,提问作者Rodrigo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:05:58