【问题标题】:How can I call a restapi function from frontend (ejs/html) [duplicate]如何从前端(ejs/html)调用restapi函数[重复]
【发布时间】:2019-07-16 21:59:00
【问题描述】:

当按下按钮以查询数据库并显示结果时,我试图基本上从 html/ejs 调用“get”方法。对不起,如果它很简单,但我无法让它工作。

我尝试require 文件并在script 标记内调用函数,但这在浏览器上不起作用。我尝试使用 <script src="text/javascript" src="filename"> 添加 js 文件,但这也会导致错误。 我构建的其余 API 使用 oracledb 与 oracle 11g (Toad) 对话。

我基本上是想在这个类中调用get函数

const employees = require('../db_apis/employees.js');

async function get(req, res, next) {
    try {
        const context = {};

        context.id = parseInt(req.params.id, 10);

        const rows = await employees.find(context);

        if (req.params.id) {
            if (rows.length === 1) {
                res.status(200).json(rows[0]);
            } else {
                res.status(404).end();
            }
        } else {
            res.status(200).json(rows);
        }
    } catch (err) {
        next(err);
    }
}
...

db_apis/employees.js

const oracledb = require('oracledb');
const database = require('../services/database');

async function find(context) {
    const baseQuery =
    `SELECT *
    FROM choice_names`;
    console.log('in find');
    let query = baseQuery;
    const binds = {};
    let additionalQuery = '\nwhere ';

    if (context.id) {
        binds.choice_name = context.id;
        additionalQuery += `choice_name = :choice_name`;
        // query += `\nwhere choice_name = :choice_name`;
    } else if (context.user) {
        binds.choice_user = context.user;
        additionalQuery += `choice_user = :choice_user`;
    } else if (context.date) {
        binds.choice_date = context.date;
        additionalQuery += `choice_date = :choice_date`;
    }

    if (context.id || context.user || context.date) {
        query += additionalQuery;
    }
    console.log(query);
    const result = await database.simpleExecute(query, binds);

    return result.rows;
}
...

路由器.js

const express = require('express');
const router = new express.Router();
const employees = require('../controllers/employees');

router.route('/employees/:id?')
    .get(employees.get)
    .post(employees.post)
    .put(employees.put)
    .delete(employees.delete);

module.exports = router;

index.ejs

...
<button onclick="get()">Click me</button>
...

【问题讨论】:

    标签: javascript node.js rest


    【解决方案1】:

    您(非常)混淆了前端和后端代码。

    express 应用程序在后端,在某个端口上运行,暴露了 /employees/:id 路由。

    但前端部分无法访问后端脚本,因此您需要从前端向该路由发出 XHR(Ajax) 请求并获取结果。

    例如,在 jQuery 中它可以是

    function get(){
       $.get('/employees/1').done(..do something..)
    }
    

    您可以参考this answer 了解如何在 Angular 上进行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 2017-08-30
      • 2022-12-18
      相关资源
      最近更新 更多