Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components' - node.js

I am trying to send files to ipfs using a website in node-js. I am using the ipfs-http-client module. When i try to access the module using require I keep getting this error :
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components' in the command prompt.
This the error message in the website :
Failed to compile
./src/components/App.js
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components'
This error occurred during the build time and cannot be dismissed.
I installed the module using the command specified in the official docs -
"npm install --save ipfs-http-client" . I can see the module in my dependencies but still getting this error.
I am a complete newbie to all this. A little help would be much appreciated. Thanks in advance.
This is how I am accessing the module :
***import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
const ipfsClient = require('ipfs-http-client');
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = ipfsClient.create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
constructor(props) {
super(props);
this.state={
buffer: null
};
}
captureFile=(event) => {
event.preventDefault()
const file = event.target.files[0]
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend=() => {
this.setState({buffer: Buffer(reader.result) })
}
console.log(event.target.files)
}
onSubmit = (event) => {
event.preventDefault()
console.log("Submitting the form...")
ipfs.add(this.state.buffer, (error,result) => {
console.log('Ipfs result', result)
if(error){
console.error(error)
return
}
})
}***

Try using earlier version I have just tried it. Do the following :
npm uninstall --save ipfs-http-client
npm i --save ipfs-http-client#33.1.1
I do not know what the problem is with the updated version but this is a quick fix up for now. And will get your code running

Import it like this:
const ipfsClient = require('ipfs-http-client');
Then create the connection:
const ipfs = ipfsClient.create(https://ipfs.infura.io:5001);
To upload:
const uploadFile = await ipfs.add({ content: file });

Maybe you're missing the babel loaders I got this working using the following:
npm i ipfs-http-client#50.1.2 #babel/core --save

If you take a look at the package at the npm website, you'll see that the newer versions import the create-function as such:
import { create } from 'ipfs-http-client'
Using this, you can simply change your code to
import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
import { create } from 'ipfs-http-client';
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
...
}

Related

Serverless Cannot Run Simple Example Query Using Node.JS

I am trying to run a simple query locally in Node JS using serverless - for the eventual purpose of uploading an Apollo Server API onto AWS Lambda.
However, I am not able to get anywhere near the deployment step as it appears that Node is unable to run a single instance of Apollo Server/Serverless locally in the first place due to a multitude of errors which shall be explained below:
Steps I have taken:
git clone the example API and follow all instructions here: https://github.com/fullstack-hy2020/rate-repository-api (I ensured everything works perfectly)
Follow all instructions on Apollographql up to "Running Server Locally": https://www.apollographql.com/docs/apollo-server/deployment/lambda/ - then run following command: serverless invoke local -f graphql -p query.json
ERROR - cannot use import statement outside module .... Solution - add "type": "module" to package.json - run command: serverless invoke local -f graphql -p query.json
ERROR - Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js... Solution - install webpack as per solution here: Serverless does not recognise subdirectories in Node then run serverless invoke local -f graphql -p query.json
ERROR - Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js
I do not know how to proceed from here, I am hoping that someone can point me in the right direction.
File Structure:
apolloServer.js:
import { ApolloServer, toApolloError, ApolloError } from '#apollo/server';
import { ValidationError } from 'yup';
import { startServerAndCreateLambdaHandler } from '#as-integrations/aws-lambda';
import AuthService from './utils/authService';
import createDataLoaders from './utils/createDataLoaders';
import logger from './utils/logger';
import { resolvers, typeDefs } from './graphql/schema';
const apolloErrorFormatter = (error) => {
logger.error(error);
const { originalError } = error;
const isGraphQLError = !(originalError instanceof Error);
let normalizedError = new ApolloError(
'Something went wrong',
'INTERNAL_SERVER_ERROR',
);
if (originalError instanceof ValidationError) {
normalizedError = toApolloError(error, 'BAD_USER_INPUT');
} else if (error.originalError instanceof ApolloError || isGraphQLError) {
normalizedError = error;
}
return normalizedError;
};
const createApolloServer = () => {
return new ApolloServer({
resolvers,
typeDefs,
formatError: apolloErrorFormatter,
context: ({ req }) => {
const authorization = req.headers.authorization;
const accessToken = authorization
? authorization.split(' ')[1]
: undefined;
const dataLoaders = createDataLoaders();
return {
authService: new AuthService({
accessToken,
dataLoaders,
}),
dataLoaders,
};
},
});
};
export const graphqlHandler = startServerAndCreateLambdaHandler(createApolloServer());
export default createApolloServer;
Serverless.yml:
service: apollo-lambda
provider:
name: aws
runtime: nodejs16.x
httpApi:
cors: true
functions:
graphql:
# Make sure your file path is correct!
# (e.g., if your file is in the root folder use server.graphqlHandler )
# The format is: <FILENAME>.<HANDLER>
handler: src/apolloServer.graphqlHandler
events:
- httpApi:
path: /
method: POST
- httpApi:
path: /
method: GET
custom:
webpack:
packager: 'npm'
webpackConfig: 'webpack.config.js' # Name of webpack configuration file
includeModules:
forceInclude:
- pg
Webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'foo.bundle.js',
},
};

Deno keeps giving me the same type of error on different modules

I am trying to connect with the Jira REST api using Deno. My Library of choice is Jira.js. I've used both installing the node_modules locally and referencing the modules through the library link. To no avail, deno gives me the same type of error.
This is my code.
//import { Version2Client } from "./node_modules/jira.js/src/index.ts";
import * as jira from "https://deno.land/x/jira#v2.10.4/src/index.ts";
const client = new Version2Client({
host: 'https://FFFFFF.atlassian.net',
authentication: {
basic: {
email: 'FFFFFFF#gmail.com',
apiToken: 'FFFFFFFF',
},
},
});
async function main() {
const projects = await client.projects.getAllProjects();
console.log(projects);
}
main();
jira.js does not support Deno directly. But you can run it with NPM compatibility mode, for that, you'll need to replace your import to use npm: specifier: npm:jira.js
import { Version2Client } from 'npm:jira.js';
const client = new Version2Client({
host: 'https://FFFFFF.atlassian.net',
authentication: {
basic: {
email: 'FFFFFFF#gmail.com',
apiToken: 'FFFFFFFF',
},
},
});
// ...

How to solve ReferenceError: gapi is not defined problem in the Next.js application?

I want add Google API (gapi) to a Next.js (node.js based) application.
So I used npm install --save #types/gapi to install the related package in my app.
But I front with the following errors:
When I use import 'gapi' from '#types/gapi':
Error » Module not found: Can't resolve '#types/gapi'
When I don't use import 'gapi' from '#types/gapi':
Error » ReferenceError: gapi is not defined
What is the reason of this error and how can I solve it?
Actually I want authenticated with auth2 by gapi after it and continue. If you know a good related sample please reference me here too please.
My codes in pages/api/test.ts:
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
function start() {
gapi.client.init({
'apiKey': '*********',
'discoveryDocs': ['https://people.googleapis.com/$discovery/rest'],
'clientId': '***********',
'scope':'https://www.googleapis.com/auth/webmasters'
}).then(function() {
return "xxxxxxxxx";
}).then(function(response:any) {
console.log(response);
}, function(reason:any) {
console.log('Error: ' + reason );
})
};
gapi.load('client', start);
}

Nest.js Testing Error: Using the "extends Logger" instruction is not allowed in Nest v8. Please, use "extends ConsoleLogger" instead

Here's the problem I have:
I am using my custom Logger in Nest.js:
export class ReportLogger extends ConsoleLogger {
verbose(message: string) {
console.log('【Verbose】Reporting', message);
super.verbose.apply(this, arguments);
}
log(message: string) {
console.log('【Log】Reporting', message);
super.log.apply(this, arguments);
}
}
And the log.interceptor.ts file:
export class LogInterceptor implements NestInterceptor {
constructor(private reportLogger: ReportLogger) {
this.reportLogger.setContext('LogInterceptor');
}
intercept(context: ExecutionContext, next: CallHandler) {
const http = context.switchToHttp();
const request = http.getRequest();
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.reportLogger.log(
`${request.method} ${request.url} ${Date.now() - now}ms`,
),
),
);
}
}
And here's the main.ts file:
async function bootstrap() {
const reportLogger = new ReportLogger();
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: {
origin: ['http://localhost', 'http://localhost:3000'],
credentials: true,
},
bufferLogs: true,
logger: reportLogger,
});
app.useGlobalInterceptors(
new LogInterceptor(reportLogger),
);
setupSwagger(app);
await app.listen(4200);
}
When I run npm run start:dev to run the Nest App on dev, everything works fine. But when I run npm run test:e2e or npm run test on testing, it shows this error:
Using the "extends Logger" instruction is not allowed in Nest v8. Please, use "extends ConsoleLogger" instead.
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AppModule],
> 12 | }).compile();
| ^
13 |
14 | app = moduleFixture.createNestApplication();
15 | await app.init();
I read the Nest.js doc again, and found the Logging breaking change in the docs. But the question is I have already made my ReportLogger extends ConsoleLogger, why this error shows again? And why it only shows in testing?
I have faced the same problem after upgrading NestJS to version 8.
Later on, I found that package #nestjs/testing had previous version installed and was not upgraded to the latest version. The reason is, previous version of NestJS testing module is using the old Logger.
In order to fix this issue, you just need to upgrade the NestJS testing module.
Run this command for Latest version:
npm i #nestjs/testing#latest
OR specific version
npm i #nestjs/testing#8.0.6 // <--- Change the NestJS version here
After this, just build and run test cases again.
External Links:
NestJS Testing NPM
even with "#nestjs/testing": "^8.0.7" this issue still occurs
class Logger implements LoggerService { ... }
await Test.createTestingModule({
imports: [ApiModule],
})
.setLogger(new Logger())
.compile();
setting logger instance solves that error on my side

How to solve this Error: Cannot find module 'ibm-watson'

I have installed ibm-watson using "npm install ibm-watson" command
I can see the folder and its file in the node_modules folder, but still showing this error.
Node version - v10.15.3
const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
const { BasicAuthenticator } = require('ibm-watson/auth');
// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
Other modules are importing fine, Only this module not importing.
internal/modules/cjs/loader.js:584
throw err;
^
Error: Cannot find module 'ibm-watson'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous>
I've just faced this issue. I did not install the correct version of the package. Please check the apidocs for Node to see the correct version of IBM Watson npm package that you need. for me I needed 5.6.0.
You can install it with the following command:
npm install ibm-watson#^5.6.0
As you are getting a token, I am going to guess that you are using Speech To Text. As the comments have suggested the failing line is const watson = require('ibm-watson'); because it isn't exported. Instead you would use, as per the API documentation - https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text?code=node#authentication:
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const { IamTokenManager } = require('ibm-watson/auth');
If it's not STT that you are using then the other services work the same way when requiring ibm-watson. Links to the API Docs can be found here - https://cloud.ibm.com/apidocs
I faced the same problem. 
After reading the code, I understood.
There is only sdk.ts file, not index.ts file.
https://github.com/watson-developer-cloud/node-sdk
// const watson = require('ibm-watson');
const watson = require('ibm-watson/sdk');
But I still got the error.
Eventually it worked if I wrote the following
import AuthorizationV1 from 'ibm-watson/authorization/v1'
import { IamAuthenticator } from 'ibm-watson/auth'
const apikey = '********'
const authorization = new AuthorizationV1({
url: 'https://iam.cloud.ibm.com/identity/token',
authenticator: new IamAuthenticator({ apikey }),
})
authorization.getToken(function (err, token) {
if (!token) {
console.log('error: ', err);
} else {
// Use your token here
}
});
But there is a CORS problem. I don't know any more.
The answer was written here. I need to do it on the server side
https://github.com/watson-developer-cloud/node-sdk/issues/884#issuecomment-515050023

Resources