[英]How to call node.js libraries from server.js?
I am new to node.js.我是 node.js 的新手。 I have an application angular front end and node.js server.
我有一个应用程序角度前端和 node.js 服务器。 And there is a js library that I am trying to get data.
还有一个我正在尝试获取数据的 js 库。
What I am trying to do is user will press a button and pass data to server.我想要做的是用户将按下一个按钮并将数据传递给服务器。 Server will pass data to a node.js library and library will return data to server.
服务器将数据传递给 node.js 库,库将数据返回给服务器。 Server will send back data to user.
服务器将向用户发回数据。
I tried to call js library from angular front end as a script.我试图从 angular 前端调用 js 库作为脚本。 But there are lots of errors because of webpack is higher than 5.
但是因为 webpack 高于 5,所以有很多错误。
node.js file: node.js 文件:
const Mam = require('@iota/mam')
const { asciiToTrytes, trytesToAscii } = require('@iota/converter')
const mode = 'private'
const provider = 'https://nodes.devnet.iota.org'
const sidekey= 'hf8685nfhfhjs9h8'
let mamState = Mam.init(provider)
const checkMam = async root=>{
const result = await Mam.fetch(root, mode)
result.messages.forEach(message => console.log('Fetched and parsed', JSON.parse(trytesToAscii(message)), '\n'))
return result.messages;
}
module.exports = { checkMam };
server.js file: server.js 文件:
const express = require('express');
const MAM_listen = require("./MAM_listen");
const app = express(),
bodyParser = require("body-parser");
port = 3080;
const users = [];
const root ='YQKXWPSBRHZXEMDUMGEHVYJKSKZVNCIBEDPYMURKLRIOOYHBCRTGGOSFGPOVSHCXIXMKKSFJIAUL9XPJZ';
app.use(bodyParser.json());
app.use(express.static(process.cwd()+"/my-app/dist/angular-nodejs-example/"));
app.get('/api/users', (req, res) => {
MAM_listen.checkMam(root).then((value) => console.log(value))
res.json(users);
});
app.post('/api/user', (req, res) => {
const user = req.body.user;
users.push(user);
res.json("user add");
});
app.get('/', (req,res) => {
res.sendFile(process.cwd()+"/my-app/dist/angular-nodejs-example/index.html")
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
I am getting this error when I am call (MAM_listen.checkMam) from app.get because the function is promise type.当我从 app.get 调用 (MAM_listen.checkMam) 时出现此错误,因为该函数是承诺类型。 Is it another way to do what I am trying to do?
这是做我想做的事情的另一种方式吗? How is this normaly done?
这通常是如何完成的? Thank you
谢谢
bodyParser
since its deprecated, change:bodyParser
因为它已被弃用,请更改:app.use(bodyParser.json());
to:到:
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
cors
to enable CORS requests, to install run the command:cors
以启用 CORS 请求,安装运行命令:npm i cors
And the in your code before the routes definitions:并且在您的代码中路由定义之前:
const cors = require('cors')
app.use(cors())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.