File not found in script - javascript

I've installed several libraries using NPM.
You have to load the file to use it there.All installed libraries are under the node_modules
The designation is like this.
<script src="../node_modules/vue/dist/vue.js"></script>
I'm sure it's on the server, I'm sure the URL of the script tag is correct
And I get the following error in the script, even though it is specified like this
login.html:45 GET https://***/node_modules/vue/dist/vue.js net::ERR_ABORTED 404
The JS file I prepared separately is loaded, but the original vue.js is not, so an error is coming back.
That's what we're trying to do with VUE.
I'm going to use Ajax to create an SPA
/* eslint-disable no-console */
const vue = require("vue"); //I added it, but it's still not working.
const axios = require("axios"); //I added it, but it's still not working.
var app = new Vue({
el: "#app",
data: {
url: "https://*****",
user: "",
password: "",
res: ""
},
methods: {
login: function () {
axios.post(this.url, {
user: this.user,
password: this.password
})
.then(function (response) {
this.res = response.data.d;
if (this.res === true) {
//true
} else {
//failed
}
})
.catch(function (error) {
alert('System error');
});
}
}
})

This is how usually use it from node_module
import Vue from 'vue'; // this will check inside node_modules for the file and include

Instead of loading the files through a script tag, use require() in your javascript. For example:
const express = require("express");
const vue = require("vue");
This will work on both the client and on the server.

Why not use a CDN?
This way, the browser will not have to download the Vue file from your server if it has already been cached. Also, you may be able to use the vue.min.js file which will load even faster than the normal Vue dist file...
For example, here is a script from cdnjs.com you could try:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"
integrity="sha256-ngFW3UnAN0Tnm76mDuu7uUtYEcG3G5H1+zioJw3t+68="
crossorigin="anonymous"></script>
Try replacing your script tag with this.

Related

Can't get .env variables to work in React using Contentful

I am trying to connect to Contentful's API in my react project. If I hardcode the space and access tokens it works fine, but if I try to use a .env file it's not getting the token.
Here's my code:
import {createClient} from "contentful";
export const client = () => {
//console.log(process.env)
let whatever = createClient({
space: process.env.REACT_APP_SPACE_ID ,
accessToken: process.env.REACT_APP_ACCESS_TOKEN,
});
return whatever;
};
export const getRecipes = async () => {
try{
const entries = await client().getEntries({
content_type: "recipe",
select: "fields"
});
return entries;
} catch(error){
console.log(`error fetch: ${error}`);
return;
}
}
I've tried various patches but nothing has worked. I have react-scripts installed as well.
I console logged the process.env and it doesn't have the token or space id.
I tried importing dotenv but that created some weird polyfill error that I've never seen before.
It could be that: your env file is not in the project folder but instead in the src/ folder...just check it once to make sure, it's a very easy mistake that a lot of people make.
Or if you have the client folder inside the server folder which is sometimes needed for deployment it might not be working because of that folder structure as well

react-native-document-picker not listing some files

I'm giving a try to react-native-document-picker. In my use case, what I want is listing some .db files so that the user is able to select one of them to import to my app. Turns out that, while using react-native-document-picker, when I navigate to the folder where the db file is, neither the .db file is shown nor the other files are.
As it's possible to see bellow, while I'm accessing the folder using Google Files, I can see the files, but I can't when I'm using react-native-document-picker:
Google files result (files being listed)
React-native-document-picker result (no files being listed)
My code is very very simple and the version I'm using is react-native-document-picker:4.0.6:
import DocumentPicker, {
DirectoryPickerResponse,
DocumentPickerResponse,
isInProgress,
types,
} from 'react-native-document-picker';
const getImportFile = async (translate) => {
try {
const file = await DocumentPicker.pick();
console.log(file);
return { success: true, error: null, payload: file };
} catch (ex) {
return { success: false, error: ex }
}
}
I'd appreciate if someone could help me with it.

Display git tag (version) on my app's login page in react

I want to display the current git tag on my app's login page,
Its built using react.
Im trying to use the 'git-rev-sync' library to do this.
but it doesnt seem to work on the client side because I keep getting errors like
'cannot find module 'children process', it works on the server side where Im able to console.log and print the tag
anyone know how to achieve this? Open to any solutions with any library
import version from 'git-rev-sync'
...
class Login extends Component {
...
render ()
...
return (
<div> my version: {version.tag()} </div>
) }
Thanks
I decided to use git-revision-webpack-plugin which creates a VERSION file (among other files) in the dist folder, and then I read the file from my client side react app:
add this to your webpack.js:
const GitRevisionPlugin = require('git-revision-webpack-plugin')
module.exports = {
plugins: [
new GitRevisionPlugin({
lightweightTags: true //I added this to get the tags as well
})
]
}
then my client side looks like this:
const [revision, setRevision] = useState('')
const fetchRevision = async () => {
let result = await fetch('/dist/VERSION')
let txt = await result.text()
txt = txt.replace(/^(.*?)(?:\-.*)?$/, '$1') //I only care for the tag.
setRevision(txt)
}
useEffect(() => {
fetchRevision()
}, [])
and then you can render the revision
One thing to notice, depending on your server, you may need to tell it to serve this VERSION file as is, so for example in express, you might find you need this:
server.get('*', (req, res, next) => {
if (/^\/dist\/*/.test(req.originalUrl)) {
const relative = req.originalUrl.replace(/\/dist(\/.*)/, '$1')
const filename = path.join(compiler.outputPath, relative)
compiler.outputFileSystem.readFile(filename, (err, result) => {
if (err) {
return next(err)
}
res.send(result)
res.end()
})
}
...
})
Hope this helps for future use.
If you used create-react-app#0.2.3 > to generate your app.
create-react-app scripts use environment variables that start with the REACT_APP_ symbol in the root .env file. create-react-app - Adding custom environment variables is a good place to dig into the details.
or just include the following in your .env file.
.env
REACT_APP_VERSION=$npm_package_version
and access it on your react login component by referring to {process.env.REACT_APP_VERSION}

Can't load scripts because of node.js

I can't use <script src="node_modules/jquery/dist/jquery.min.js"></script>
in my index.html file because of:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8080/node_modules/jquery/dist/jquery.min.js
This happens because of my else statement in server file code:
var http = require('http')
var url = require('url')
var fs = require('fs')
var server = http.createServer((req, res) => {
let parsedUrl = url.parse(req.url, true)
if (parsedUrl.pathname === '/') {
console.log('home page')
fs.readFile('./index.html', (err, data) => {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(data)
})
} else if (parsedUrl.pathname === '/readJson') {
console.log('read json')
fs.readFile('./data.json', (err, data) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(data)
})
} else {
console.log('We can\'nt load any resources because of this statement')
res.writeHead(404)
res.end()
}
})
server.listen(8080)
I've read about how to fix this problem when using express module. Is there any way to solve the problem without using that module?
The easiest way would be to simply load jQuery from a CDN instead of serving it from your own server. This is a widely accepted best practice.
Example:
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
You can find various options for loading jQuery from a CDN here: https://code.jquery.com
If you create an HTTP server like in your code example and want it to serve jQuery, then you'd have to read the jquery.min.js using fs.readFile and serve its contents, just like you're doing with your data.json file.
I recommend the use a CDN instead. If you install the jQuery module you can use it for your back-end JavasSript. However you want to use it on the front-end. You are using NodeJS as web server to serve a HTML page. The http module doesn't know anything about other files because it only read the index.html.
So you might wanna search for a solution to read/serve a complete folder. Withing this folder, lets call it public, you can store you HTML, CSS and JS files that are public available. Since the HTTP module knows about the entire folder all files can be used on the front-end. This is also a good solution to separate your back-end en front-end JavaScript.

Using the AWS SDK for Javascript with Vue.js 2.0

I'm accessing API's hosted by AWS API Gateway with Vue.Js.
There's some pretty good instructions here http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk-javascript.html.
I have a bunch of different components, each of which will get data from a different API GET call. Initially I tried adding all the script files to my index.html and doing the following:
RetailerDetails.vue:
<script>
export default {
name: 'RetailerDetails',
mounted() {
var apigClient = apigClientFactory.newClient({
accessKey: 'blah',
secretKey: 'blah',
});
apigClient.businessGet = function (params, body, additionalParams) {
if (additionalParams === undefined) { additionalParams = {}; }
apiGateway.core.utils.assertParametersDefined(params, [], ['body']);
var businessGetRequest = {
verb: 'get'.toUpperCase(),
path: pathComponent + uritemplate('/business').expand(apiGateway.core.utils.parseParametersToObject(params, [])),
headers: apiGateway.core.utils.parseParametersToObject(params, []),
queryParams: apiGateway.core.utils.parseParametersToObject(params, []),
body: body
};
return apiGatewayClient.makeRequest(businessGetRequest, authType, additionalParams, config.apiKey);
};
},
}
That didn't work, I got ReferenceError: apigClientFactory is not defined.
So then I tried taking the script tags out of my index.html and adding the following lines to my component:
require('../assets/js/lib/axios/dist/axios.standalone.js');
require('../assets/js/lib/CryptoJS/rollups/hmac-sha256.js');
require('../assets/js/lib/CryptoJS/rollups/sha256.js');
require('../assets/js/lib/CryptoJS/components/hmac.js');
require('../assets/js/lib/CryptoJS/components/enc-base64.js');
require('../assets/js/lib/url-template/url-template.js');
require('../assets/js/lib/apiGatewayCore/sigV4Client.js');
require('../assets/js/lib/apiGatewayCore/apiGatewayClient.js');
require('../assets/js/lib/apiGatewayCore/simpleHttpClient.js');
require('../assets/js/lib/apiGatewayCore/utils.js');
require('../assets/js/custom/apigClient.js');
This don't work either, now I get ReferenceError: Can't find variable: CryptoJS
which from what I understand is because I haven't referenced the flles properly?
What do I need to do?
Don't put javascript files in the assets folder. Put them in the static folder instead. If you are using the CLI install, Webpack sorts through the assets and takes care of things like image and fonts, but not javascript files.
When I put the files in the /static/ or something like /static/js/ and then bring them in with:
<script type="text/javascript" src="/static/apigClient.js"></script>
the functions are available to my Vue components. Maybe there's a nicer way that doesn't pollute the global namespace, but this is a pretty easy solution (assuming it also works for you).

Categories