[英]How to use variable from node server into another javascript file
Hello I'm new to node js, and came across using it while making an rtc project where I have to make calls, I use rtcmulticonnection library which has server.js and index.html您好,我是 node js 的新手,在制作 rtc 项目时遇到了使用它,我必须在其中进行调用,我使用具有 server.js 和 index.html 的 rtcmulticonnection 库
In index.html I have some data I want to push into the mysql database, so I use this code in server.js:在 index.html 中,我有一些数据要推送到 mysql 数据库中,因此我在 server.js 中使用了以下代码:
const mysql = require('mysql');
const connectionsql = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test'
});
connectionsql.connect((err) => {
if (err) throw err;
console.log("Connected!");
});
The above code is for connection to mysql in server.js so now I have some data in index.html (coming different each time).. I want to push into the database, how can i send that to server.js file and make a commit?上面的代码用于在 server.js 中连接到 mysql 所以现在我在 index.html 中有一些数据(每次都不同)。我想推送到数据库中,我如何将它发送到 server.js 文件并制作提交? i cannot use connectionsql into the script tag in index.html(script tag) file so can create a query like this:我不能在 index.html(script tag) 文件中的 script 标签中使用 connectionsql,因此可以创建这样的查询:
const call = { room_id: caller_id, callee_id: callee_id };
connectionsql.query('INSERT INTO chat_calls SET ?', call, (err, res) => {
if(err) throw err;
console.log('Last insert ID:', res.insertId);
});
You cannot connect to the SQL
server directly from client side.您不能直接从客户端连接到SQL
服务器。
I don't know much about your server set up, but probably the way to go would be to set up an API endpoint on your server that the client side can post data to.我不太了解您的服务器设置,但可能要走的路是在您的服务器上设置一个 API 端点,客户端可以将数据发布到该端点。 Then, your server can insert the data it received from the client into the DB.然后,您的服务器可以将从客户端接收到的数据插入到数据库中。
EDIT编辑
A very common approach is to use an express
server:一种非常常见的方法是使用express
服务器:
https://www.npmjs.com/package/express https://www.npmjs.com/package/express
Follow the guide setting up your express
server, and then register an endpoint for your client to post to.按照指南设置您的express
服务器,然后为您的客户端注册一个端点以进行发布。
There are many guides on the internet that can help you set it all up.互联网上有许多指南可以帮助您进行设置。 If you run into trouble, I would suggest creating separate questions on SO for that.如果您遇到麻烦,我建议为此创建关于 SO 的单独问题。
Any further help would be beyond the scope of this question.任何进一步的帮助都超出了这个问题的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.