Problem using a npm package in React - says "TypeError: require is not a function" - node.js

I'm trying to use the package lastfm within a React app.
I have installed it with
npm install lastfm
The official doc says it should be used like this :
var LastFmNode = require('lastfm').LastFmNode;
var lastfm = new LastFmNode({
api_key: 'abc',
secret: 'secret'
});
And this is how I use it in my React code :
import {LASTFM_API,LASTFM_API_SECRET} from "./Constants";
import {LastFmNode} from 'lastfm';
export class Lastfm {
static scrobbleTrack(track): void {
var lastfm = new LastFmNode({
api_key: LASTFM_API,
secret: LASTFM_API_SECRET,
useragent: 'appname/vX.X MyApp'
});
}
}
Which fires this error (from the package) :
TypeError: require is not a function at lastfm-request.js:3
I'm quite new to React and NPM.
I wonder if there is some kind of incompatibility ?
How could I make this work ?
Thanks !

The package is to be used on Node server and not on React App.
EDIT
Hi, sorry i cannot comment because my points are less.
You can not use that one as well because that is also a node package. If you see a syntax where you have to use: require('something'); usually means it is a node package because in React, your syntax for importing is something like this: const abc from 'xyz';

Related

Property 'register' does not exist on type 'NestExpressApplication'

According to nestjs documentation I want to use fastify-helmet in order to config contentSecurityPolicy.
first I installed the following package:
$ npm i --save fastify-helmet
in my main.ts I registered fastifyHelmet but it throw the following error :
Property 'register' does not exist on type 'NestExpressApplication'
async function bootstrap() {
const logger = new Logger('bootstrap')
const app = await NestFactory.create<NestExpressApplication>(AppModule);
await app.register(fastifyHelmet); // this line thorw error
...
const PORT = process.env.PORT
await app.listen(PORT);
logger.log(`Application is start on port : ${PORT}`)
}
bootstrap();
The problem is that you are trying to register a fastify package to your express based app which does not work.
There are 2 possibilities to fix your issue:
Use a express compatible package (for example helmet: npm i --save helmet) and then register it with: app.use(helmet) (express does not use .register but .use)
Change your NestJS App to Fastify: (npm i --save #nestjs/platform-fastify) and then: const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter()); -> then the fastify-helmet package (and .register) should work!
More details about using fastify instead of express are available at the official documentation page: NestJS Documentation

How do I fix "unexpected token 'export'" error when I try to use uuid package?

I'm working in a vue.js application with node.js in the backend. We've installed the npm package uuid in the backend but it's not working.
Our package.json file in the backend contains this:
"uuid": "^8.2.0",
In our controller, in the constructor, we have this:
this.uuid = require("uuid");
And we use it like this:
const id = this.uuid.v1();
The problem is, when we call the endpoint on the backend, we get this error:
C:\...\backend\node_modules\uuid\dist\esm-browser\index.js:1
export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
Googling this issue, the only solutions I've found involve importing v1 specifically, such as this:
import {v1 as uuid} from "uuid";
But since we're using node.js on the backend, we get this error:
SyntaxError: Cannot use import statement outside a module
How can I solve this problem?
I have been there. Used this approach:
const uuid = require('uuid');
const newUuid = uuid.v4();
You may use .v1() instead of .v4().
You should first export your functions (that you need in other modules) in v1.js like below-
function xyz() {
}
module.exports = xyz;
You can then use this in the respective files as-
const xyz = require(‘../pathname’);

How to use node.js module with Angular 6?

I am newbie in Angular 6 and TypeScript. Can someone show me the right way to use node.js third-party module in Angular 6?
For example i want to create component with ability to consume and make requests to SOAP wsdl methods.
Did installed it by adding to package.json with npm install.
Trying to use node-soap npm module like this:
import { Injectable } from '#angular/core';
import * as soap from 'node-soap';
#Injectable({
providedIn: 'root'
})
export class MySoapService {
constructor() { }
getOrderInfo() {
const url = 'http://my-example-api.com/WCF/ClientService.svc?singleWsdl';
let args = {
login: 'login',
password: 'password',
orderNumber: 'F976638'
};
soap.createClient(url, function(err, client) {
client.GetOrderInfo(args, function(err, result) {
console.log(result);
});
});
};
}
Then inject this service into component and render it, just to test the service...
But got some error during ng serve:
ERROR in ./node_modules/node-soap/client.js
Module not found: Error: Can't resolve 'http' in '/home/cadistortion/WebstormProjects/my-ng-app/node_modules/node-soap'
Thank you!
it's easy, in your url have your API node.
You go need more, express.js(or other) for get work.
BD - like MongoDB or other or Json.
See this vídeo and other the same user https://www.youtube.com/watch?v=M-G48Gf2Xl0
is complete how create blog using MEAN Stack

App Object in Electron Module and getAppPath throws Error

I have a strange problem with my application. I get an error, and I can't solve it. First at all, I installed a new project, so everything is clean. Someone sent me this repo to use for an Angular, Electron and Nodejs Application. Everything worked fine, but then I decided to install an embedded database like sqlite3. For this I found NeDB, and the module is perfect for my needs. First I had the problem, has nothing to do with my general problem, that I can't create a database file. So I read that I can only create files in my application path, because something about Electron and that's working in a browser.
I found the getAppPath() method that is implemented in my app object from the Electron module. Here starts the problem. For hours I tried to get the application path from this object. Finally, I wrote this code.
import { Injectable } from '#angular/core';
var nedb = require('nedb');
import { app } from 'electron';
import * as path from 'path';
#Injectable()
export class DatabaseService {
app: typeof app;
Database: any;
constructor() {
this.app = window.require("electron").app;
this.Database = new nedb({ filename: path.join(this.app.getAppPath(), '/diary.db'), autoload: true, timestampData: true });
var scott = {
name: 'Scott',
twitter: '#ScottWRobinson'
};
this.Database.insert(scott, function(err, doc) {
console.log('Inserted', doc.name, 'with ID', doc._id);
});
}
}
And I get this error.
I found this posting, but I don't really understand what the post is trying to tell me. I followed the links, but nothing seems to help. Anyone have an idea?

Router is not defined in KOA2

I have two files, one of them is the app.js and the otherone is api.js.
In the first file I have :
app.use(setHeader)
app.use(api.routes())
app.use(api.allowedMethods())
And in api.js I have:
import KoaRouter from 'koa-router';
const api = new Router();
//Validatekey
const validateKey = async (ctx, next) => {
const { authorization } = ctx.request.headers;
console.log(authorization);
if (authorization !== ctx.state.authorizationHeader) {
return ctx.throw(401);
}
await next();
}
api.get('/pets', validateKey, pets.list);
When I run the project a error message is throw: Router is not defined.
But If I write both files together, the application go fine.
Anybody knows the problem?
I have solved with var Router = require('koa-router')
The import is currently not implemented in nodejs, neither is it supported in the latest ES2015(ES6).
You will need to use a transpiler like Babel to use import in code.I advice that avoid transpiler as it cause performance issues on production just go with require and it will work.
Obviously Nodejs does not support import / export syntax and using require will solve your problem.
However it is possible to make import work on Node.js by using babel transformers.
Look the following answer for more information https://stackoverflow.com/a/37601577/972240

Resources