Vue Error - Can't resolve 'https' when importing package - node.js

I'm trying to make a Vue project and use an npm package for connecting to the retroachievements.org api to fetch some data, but I'm getting an error. Here's my process from start to finish to create the project and implement the package.
Navigate to my projects folder and use the vue cli to create the project: vue create test. For options, I usually chose not to include the linter, vue version 2, and put everything in package.json.
cd into the /test folder: cd test and install the retroachievements npm package: npm install --save raapijs
Modify App.vue to the following (apologies for code formatting, not sure why the post isn't formatting/coloring it all properly...):
const RaApi = require('raapijs');
export default {
name: 'App',
data: () => ({
api:null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
}
run `npm run serve' and get the error:
ERROR in ./node_modules/raapijs/index.js 2:14-30
Module not found: Error: Can't resolve 'https' in 'C:\Projects\Web\test\node_modules\raapijs'
I'm on Windows 10, Node 16.17.0, npm 8.15.0, vue 2.6.14, vue CLI 5.0.8, raapijs 0.1.2.
The first solution below says he can run it without error but it looks like the exact same code as I'm trying. Can anyone see a difference and a reason for this error?
EDIT: I reworded this post to be more clear about my process and provide more info, like the versions.

This solution works for me. I installed raapijs with npm install --save raapijs command. Then in my Vue version 2 component I used your code as follow:
const RaApi = require('raapijs');
export default {
data: () => ({
api: null,
user: '<USER_NAME>',
apiKey: '<API_KEY>',
}),
created() {
this.api = new RaApi(this.user, this.apiKey);
},
};

It seems the raapijs package was designed to be used in a Node environment, rather than in Vue's browser based environment, so that's the reason I was getting an error. The package itself was looking for the built in https package in Node, but since it wasn't running in Node, it wasn't finding it.
So I solved my problem by looking at the package's github repo and extractingt he actual php API endpoints that were being used and using those in my app directly, rather than using the package wrapper. Not quite as clean and tidy as I was hoping but still a decent solution.

Related

Gatsby Source Drupal not fetching data when trying to deploy to netlify/heroku

I have a site running Gatsby and Gatsby-Source-Drupal7, it is a plugin that uses Graphql to make an axios get request to https://stagingsupply.htm-mbs.com/restws_resource.json and uses the json data to query. I am able to run it just fine on my computer by going to localhost:8000 and it creates over 200k nodes, but when I try to deploy on any cloud service provider like Gatsby Cloud or Netlify it doesn't fetch any nodes or data at all from the site.
Warning from console
Starting to fetch data from Drupal
warn The gatsby-source-drupal7 plugin has generated no Gatsby nodes. Do you need
it?
Code
code from gatsby config
module.exports = {
siteMetadata: {
title: `new`,
siteUrl: `https://www.yourdomain.tld`,
},
plugins: [
{
resolve: `gatsby-source-drupal7`,
options: {
baseUrl: `https://stagingsupply.htm-mbs.com/`,
apiBase: `restws_resource.json`, // optional, defaults to `restws_resource.json`
},
},
]
}
gatsby-config.js from node_modules/gatsby-source-drupal7
const createNode = actions.createNode; // Default apiBase to `jsonapi`
apiBase = apiBase || `restws_resource.json`; // Fetch articles.
// console.time(`fetch Drupal data`)
console.log(`Starting to fetch data from Drupal`);
const data = yield axios.get(`${baseUrl}/${apiBase}`, {
auth: basicAuth
});
const allData = yield Promise.all(_.map(data.data.list,
Link to repo that works on local computer https://github.com/nicholastorr/gatsby-d7
any and all help will be appreciated
As you pointed out, you've played around with the Node versions using NODE_ENV and engines workarounds. My guess also relies on a mismatching Node version between environments but as Netlify docs suggests, there are only two ways of customizing Node versions to manage dependencies.
Set a NODE_VERSION environment variable.
Add a .node-version or .nvmrc file to the site’s base directory in your repository. This will also tell any other developer using the
repository which version of Node.js it depends on.
Without seeing your Netlify build command (to see the NODE_VERSION) there's no .node-version nor .nvmrc in your repository. I'd try creating it at the root of the project with the v14.17.1 in it and trying a fresh install.
In addition, double-check other server-related conflicts like IP-blocking, etc.
Error was nothing Gatsby or Node related, my site was block the IP of the server :>

Error API body type after build with node adapter

My app on SvelteKit + ts. I build npm run build (node adapter), with npm run preview (and with npm run dev) everything works. With node build
export async function post ({body}) {
try {
const login = body.get ('login');
error TypeError: body.get is not a function.
Content-Type request: application / x-www-form-urlencoded. Body is Uint8Array(34) in building app.
As I understand it, you need to screw the bode-parser somewhere. Or how to solve this?
Thanks!
Update #sveltejs/kit to 1.0.0-next.165 fix it =)

Question regarding NPM, ReactJS, and installed packages both globally, and locally

Question regarding NPM, ReactJS, and installed packages both globally, and locally. I have done quite of bit of searching and found no real resolution. Here's my main App component:
import React, { Component } from 'react'
// import ReactLogger from 'react-terminal-logger/console-logger'
import 'whatwg-fetch'
import Intro from '../Intro/Intro'
import './app.css'
// ReactLogger.config({
// visible: ['log', 'error', 'info', 'warn', 'logr'],
// save_logs: false,
// only_msg: true,
// port: 1234,
// stacktrace_hide: true,
// })
// ReactLogger.start()
class App extends Component {
state = {
series: [],
logs: [],
}
componentDidMount() {
// Hook(window.console, (log) => {
// this.setState(({ logs }) => ({ logs: [...logs, Decode(log)] }))
// })
fetch('http://api.tvmaze.com/search/shows?q=Vikings').then((response) => {
console.log(response)
// logr(response)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">TV Series List</h1>
</header>
<Intro message="Here you can find all you most loved series!" />
The length of the series array is - {this.state.series.length}{' '}
</div>
)
}
}
export default App
Any time I install a package globally, so I can reuse it in other projects I end up with an error when I try to start the server. Such as the logging package (above) react-terminal-logger. I used the following steps:
npm install -g react-terminal-logger
added import and initialized components as per instructions
tried to use component (eg. logr(response))
I end up with the same error at compile time no matter what I installed globally and add to my project.
C:\Users\DawsonSchaffer\Documents\ProjectsDirectory\Projects\reactjsx-tutorial-old\node_modules\react-scripts\scripts\start.js:19
throw err;
[Error: ENOENT: no such file or directory, stat 'C:\Users\DawsonSchaffer\Application Data'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Users\\DawsonSchaffer\\Application Data'
}
My global package prefix points to "C:\Users\DawsonSchaffer\AppData\Roaming\npm" which is the default. If I simply remove the components use by it commenting out everything works.
How do I resolve this? What is the proper way to install a new global package and add it to an existing project? What am I missing? Any help would be greatly appreciated.
One other note, if I install the component locally in my project it works fine. Overall point though is too not have to install it in every project.
Thanks
Dawson
The first thing to understand here is that the global install option of common JS package managers is not intended to facilitate shared project dependencies. To clarify, from NPM itself:
Installing a package globally allows you to use the code in the package as a set of tools on your local computer.
With that out of the way, the optimization you're looking for is a real one, but for different reasons than you may think. When thinking about dependency management, you're really thinking about a small subset of pros and cons related to deciding whether you want use a mono-repo, multi-repo (microservices) or some hybrid.
If you're dealing with entirely different projects that are using the same dependency, then ignore the previous paragraph as they should definitely each manage their own dependencies independently.
Maybe this answer could help you:
How do I install a module globally using npm?
Usually, global installation are meant to be for CLI tools or executable tools.
So I finally got it all straightened out. I uninstalled react, react-dom, and react-scripts from global; leaving me with only create-react-app. I created an empty project called react-boilerplate, and installed react, react-dom, react-scripts, and react-router-dom in the new project. I then uploaded to my GitHub account so I have a common starting point for new projects. Should have thought about this before but it took me a while to wrap my head around everything. Now I can update my boilerplate as needed, and use it to clone as a starting point for new projects. Yeah!
Thanks to everyone especially Dennis G for all his help!!
Dawson

NPM and NodeJS Compatibility: NodeJS works from PM prompt, but not script

I am attempting to get a lighthouse script running in Node.JS (which I am new to). I followed the intial instructions here https://github.com/GoogleChrome/lighthouse/blob/master/docs/readme.md#using-programmatically. I was able to complete the prior steps in the package manager console (Visual Studio 2017):
npm install -g lighthouse
lighthouse https://airhorner.com/
//and
lighthouse https://airhorner.com/ --output=json --output-path=./report/test1.json
However, I do get an initial warning that NPM only supports Node.JS in versions 4 through 8 and recommends a newer version. The problem is I am running Node v12 and NPM v5 - both the latest.
When I create a script version like below (app.js)
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const config = {
extends: 'lighthouse:default',
settings: {
emulatedFormFactor: 'desktop',
onlyCategories: 'performance',
output: 'json',
outputPath: './report.json'
}
};
function launchChromeAndRunLighthouse(url, opts = null, config) {
return chromeLauncher.launch().then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, config).then(results => {
return chrome.kill().then(() => results.lhr);
});
});
}
// Usage:
launchChromeAndRunLighthouse('https://airhorner.com/', config).then(results => {
// Use results!
});
And run the command
C:\src\project> node app.js
I get the error - Cannot find module 'lighthouse'
don't install lighthouse locally use it inside your working dir .
first start by running npm init that will create the package.json file inside the current working dir
then npm install --save lighthouse will download it and save it to node_modules now you can use it locally inside your working dir
it should look something like this
app.js
package.json
node_modules/
then run node app.js

'Cannot find module' error using karma-browserify on Windows

I'm attempting to set up unit testing on an Angular/Browserify project using Karma, Karma-Jasmine, and Karma-Browserify. I'm on a Windows machine, for reference. karma-cli is on my global npm path, and karma, karma-jasmine, karma-browserify, and browserify are all local npm installs, using -D.
I'm trying to pull in a single spec file, which looks like:
var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');
describe('PhoneListCtrl', function() {
var scope,
ctrl;
beforeEach(function() {
scope = {};
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope).not.toBe(undefined);
});
});
And I get the following error every time:
Uncaught Error: Cannot find module 'Cc/gGH'
I get this exact same error after cloning the following repos, installing karma and all plugins, and attempting to run their example test suites:
https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify
What on earth am I doing wrong? The test spec module is found correctly, and karma seems to be finding all necessary plugins/preprocessors, but it appears that karma-browserify is tripping on the require statement in a spec every time, for reasons I cannot fathom.
I've uninstalled and reinstalled karma and all related plugins numerous times now, to no avail.
I managed to find a solution. The issue was caused by karma-browserify's own module name hashing function, which is incompatible with newer versions of browserify. There's a fork that deals with it by using browserify's hashing function:
https://github.com/voidlock/karma-browserify/commit/3afe3b7485f2e4723bba5ad1c5a730d560b8c234
There's a pull request pending but in the meantime you can use the fork by placing
"karma-browserify": "https://github.com/voidlock/karma-browserify/tarball/use-browserify-hash-function"
in your package.json (dev)dependencies section.

Resources