html script post,How to link Node.js Post script to HTML form?

作者探讨了如何将创建的RESTful API与HTML文件集成,以便在用户注册时保存数据到MongoDB。他们询问了如何在HTML中调用API,并关心是否需要保持数据库连接的持久性,以及如何优化资源消耗。讨论了可能的解决方案和改进方法,涉及API设计和前端调用的最佳实践。
摘要由CSDN通过智能技术生成

I have created a REST full APi, which works as I would be expecting if I am running Postman. I run the Test from an index.js file which would have the routes saved as per below file.

const config = require('config');

const mongoose = require('mongoose');

const users = require('./routes/users');

const auth = require('./routes/auth');

const express = require('express');

const app = express();

//mongoose.set();

if (!config.get('jwtPrivateKey'))

{

console.log('Fatal ERRORR: jwtPrivateKey key is not defined')

process.exit(1);

}

mongoose.connect(uri ,{

useNewUrlParser: true,

useUnifiedTopology: true,

useCreateIndex: true

})

.then(()=>console.log('Connected to MongoDB...'))

.catch(err=> console.log('Not Connected, bad ;(', err));

app.use(express.json());

//THis is only for posting the user, e.g. Registering them

app.use('/api/users', users);

app.use('/api/auth', auth);

const port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Listening on port ${port}...`));

The real code is happening here. Testing this in Postmon I could establish, that the values are saved in MongoDB.

router.post('/', async (req, res) => {

//validates the request.

const { error } = validate(req.body);

if (error) return res.status(400).send(error.details[0].message);

let user = await User.findOne({email: req.body.email});

if (user) return res.status(400).send('User Already Register, try again!');

user = new User(_.pick(req.body, ['firstName','lastName','email','password','subscription']));

const salt = await bcrypt.genSaltSync(15);

user.password = await bcrypt.hash(user.password, salt);

//Here the user is being saved in the Database.

await user.save();

//const token = user.generateAuthToken();

//const token = jwt.sign({_id: user._id}, config.get('jwtPrivateKey'));

const token = user.generateAuthToken();

//We are sending the authentication in the header, and the infromation back to client

res.header('x-auth-token',token).send( _.pick(user, ['_id','firstName','lastName','email','subscription']));

});

Now my question's are:

How can I call the second code block from a , in one particular html file. When using Action="path to the users.js", the browser opens the js file code but doesn't do anything.

Do I need to rewrite the Post block part so that it would as well include the connection details to the DB? And would this mean I would keep open the connection to MongoDB once I insert Read etc.? Wouldn't this eat a lot of resources if multiple users would e.g. log in at the same time?

Or is there a way how I can use the index.js + the users.js which is refereed in the index.js file together?

All of these are theoretical questions, as I am not quite sure how to use the created API in html, then I created as walking through a tutorial.

Do I need to change the approach here?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值