【发布时间】:2020-01-19 17:18:57
【问题描述】:
我是新学习 NodeJS + Express,现在我正在尝试构建一个简单的注册表单,但我不断收到与此表单和其他表单相同的错误:
无法发布 /registerauth
我在 stackoverflow 和其他网站上查看了几十个类似的问题,但我没有找到适用于我的案例的答案。
这是表格:
<form id="register-form" class="panel-form" action="/registerauth" method="POST">
<input type="text" name="register-username" id="register-username" class="fill-input" placeholder="Username *" autofocus="true" maxlength="15" required>
<input type="password" name="register-password" id="register-password" class="fill-input" placeholder="Password *" maxlength="30" required>
<button type="submit">Register</button>
</form>
我的 app.js 文件:
const express = require('express');
const app= express();
const path = require('path');
const port = process.env.PORT || 3000;
const login = require('./routes/login'); /*MODULE THAT HAS THE CONTROLLER CODE*/
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname , 'public')));
app.post('/registerauth',function (req,res,next){ /*TRIED THIS BUT DIDN'T WORK*/
console.log("testing");
res.json(req.body);
})
app.use('/login', login); /*TRIED CALLING THE MODULE THAT HAS THE CONTROLLER AND DELETING THE LINE ABOVE BUT DIDN'T WORK*/
app.listen(port, ()=> console.log(`server started on port ${port} `))
具有控制器代码但甚至没有被调用的模块:
const express = require('express');
const oracledb = require('oracledb');
const router = express.Router();
const dbConfig =require('../dbconfig.js') ;
class Cliente{
constructor(username,password,nombre,email){
this.username = username;
this.password=password;
this.nombre=nombre;
this.email=email;
}
}
let conexion;
router.post('/registerauth',async(req,res,next)=>{ /*all this is not working neither*/
try{
console.log("THIS IS NOT WORKING");
cliente = new Cliente(req.body.username, req.body.password,req.body.nombre,req.body.email);
conexion= await oracledb.getConnection(dbConfig);
const result = await conexion.execute(
`INSERT INTO Cliente values (${cliente.username}, ${cliente.password},
${cliente.nombre}, ${cliente.email})`
);
} catch(err){
console.error(err);
}finally{
conexion.close();
}
})
module.exports = router;
我的项目文件夹是这样组织的:
/
node_modules
public/
css/
media/
scripts/
index.html (just the file inside public folder)
register.html (just the file inside public folder THIS IS THE REGISTER FORM FILE)
routes/
api/
login.js
app.js
dbconfig.js
package-lock.json
package.json
注意:我在我的项目中使用不同的操作方法创建了其他表单,它们都给出了相同的错误
【问题讨论】:
-
嗨@Runsis,当您单击表单提交按钮时,您是否在控制台中看到字符串
testing登录到您的节点服务器以获取路由registerauth?你是如何启动你的节点服务器的? -
@mgarcia 嗨,我在终端和浏览器控制台中都没有看到任何控制台消息。我正在使用 nodemon app.js 启动我的节点服务器,并且可以正常工作,例如它会加载模板,但它不适用于我的要求:/
-
您在代码中定义了两条路由,一条在
app.js中,另一条在您的控制器文件中。app.js中的路由是"/registerauth"但控制器文件中的路由是"/login/registerauth"因为这一行:app.use('/login', login); -
代码中一些重要的cmets:对于Web应用程序,您应该使用连接池来提高性能和可伸缩性。对于 SQL 语句,您必须使用绑定变量来确保安全性(和可伸缩性)而不是
${cliente.username}。查看 node-oracledb doc 和 examples。还要检查Creating a REST API with Node.js and Oracle Database
标签: javascript html node.js forms express