【问题标题】:How to call node.js libraries from server.js?如何从 server.js 调用 node.js 库?
【发布时间】:2021-12-09 16:00:24
【问题描述】:

我是 node.js 的新手。 我有一个应用程序角度前端和 node.js 服务器。 还有一个我正在尝试获取数据的 js 库。

我想要做的是用户按下按钮并将数据传递给服务器。 服务器会将数据传递给 node.js 库,而库会将数据返回给服务器。 服务器会将数据发回给用户。

我尝试从 Angular 前端调用 js 库作为脚本。但是由于 webpack 高于 5 会出现很多错误。

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 文件:


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}`);
});

当我从 app.get 调用 (MAM_listen.checkMam) 时出现此错误,因为该函数是 promise 类型。这是做我想做的事情的另一种方式吗?这通常是如何完成的? 谢谢

error

【问题讨论】:

    标签: javascript node.js angular


    【解决方案1】:
    1. 不要使用bodyParser,因为它已被弃用,请更改:
    app.use(bodyParser.json());
    

    到:

    app.use(express.json());
    app.use(express.urlencoded({ extended: true }))
    
    1. 添加 cors 以启用 CORS 请求,安装运行命令:
    npm i cors
    

    在你的代码中路由定义之前:

    const cors = require('cors')
    
    app.use(cors())
    

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2011-12-27
      • 2013-06-18
      • 2015-01-07
      • 2017-06-22
      相关资源
      最近更新 更多