ReactJS Error: only absolute urls are supported - reactjs

I am trying to pull in the current URL to use in my fetch command, but I received an error when attempting to parse the URL via window.location. It appears that this URL use is not allowed, but I'm not sure of another alternative to achieve what I'm looking for. I'm avoiding setting a string so I can adapt my React setup to multiple environments.
Error:
Error: only absolute urls are supported
Line creating the error:
console.log(protocol + '//' + hostname + ':' + port + '/api' + window.location.search);
Variables:
var urlPath = window.location.pathname;
var hostname = window.location.hostname;
var protocol = window.location.protocol;
var port = window.location.port;

I prefer dotenv. Then all you need to do is to create a .env file. There are a couple ways of loading it into your app.
Webpack(not the npm package listed above, instead is webpack-dotenv-plugin)
import DotenvPlugin from 'webpack-dotenv-plugin';
plugins: [
new DotenvPlugin({
sample: './.env.default',
path: './.env',
}),
Not webpack
As early as possible:
require('dotenv').config()

Related

firebase cloud functions: cannot read property 'environment' of undefined

am getting this error while I'm trying to deploy to a new firebase project using
firebase deploy --only functions command. I have two projects in use, one dev and one prod, I was working on prod and deploy worked well now too but when I added this project dev the deploying keeps working well in prod but in this new project dev no. I instead get this error:
Error: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'environment' of undefined
at Object. (/home/projectId/Bitbucket/project-backend/functions/lib/db.js:6:35)
I added the key and eveything in cert/dev/firebase-dev.json in order to work.
The file db.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.db = void 0;
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const dir = functions.config().app.environment;
const certFile = `firebase-${dir}.json`;
//using admin SDK
const serviceAccount = require(__dirname + `/../cert/${dir}/${certFile}`);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
.....
Any Idea? Thanks.
Since the error is cannot read property 'environment' of undefined and in your code we see
const dir = functions.config().app.environment;
the error seems to come from the environment configuration.
You should double check that the environment configuration is correctly set in the dev environment/project.
For that, you should use the firebase functions:config:get CLI command, as explained in the doc.

Configure the sw-precache WebPack plugin to load a server rendered page as the navigateFallback route

consider the following scenario:
My express server dynamically generates HTML for the "/" route of my single page application.
I would like to re-serve this same generated HTML as the service worker navigateFallback when the user is offline.
I'm using https://www.npmjs.com/package/sw-precache-webpack-plugin in my webpack configuration.
If I generate an index.html via html-webpack-plugin, say, and set index.html as my navigateFallback file, that generated file gets served correctly by the service worker.
However, I can see no way to cause the on-the-fly rendered index html (what the live server returns for the "/" path) to be cached and used as the offline html.
Use dynamicUrlToDependencies option of Service Worker Precache to cache your route url and its dependencies. Then set navigateFallback to '/' and navigateFallbackWhitelist to a regex matching your sublinks logic.
Take this configuration : (Add const glob = require('glob') atop of your webpack config)
new SWPrecacheWebpackPlugin({
cacheId: 'my-project',
filename: 'offline.js',
maximumFileSizeToCacheInBytes: 4194304,
dynamicUrlToDependencies: {
'/': [
...glob.sync(`[name].js`),
...glob.sync(`[name].css`)
]
},
navigateFallback: '/',
navigateFallbackWhitelist: [/^\/page\//],
staticFileGlobsIgnorePatterns: [/\.map$/],
minify: false, //set to "true" when going on production
runtimeCaching: [{
urlPattern: /^http:\/\/localhost:2000\/api/,
// Use network first and cache as a fallback
handler: 'networkFirst'
}],
})
That use case should be supported. I have an example of something similar using the underlying sw-precache library, and I believe the syntax should be equivalent when using the Webpack wrapper.
In this case, /shell is the URL used for dynamically generated content from the server, constituting the App Shell, but it sounds like your use case is similar, with / instead of /shell.
{
// Define the dependencies for the server-rendered /shell URL,
// so that it's kept up to date.
dynamicUrlToDependencies: {
'/shell': [
...glob.sync(`${BUILD_DIR}/rev/js/**/*.js`),
...glob.sync(`${BUILD_DIR}/rev/styles/all*.css`),
`${SRC_DIR}/views/index.handlebars`
]
},
// Brute force server worker routing:
// Tell the service worker to use /shell for all navigations.
// E.g. A request for /guides/12345 will be fulfilled with /shell
navigateFallback: '/shell',
// Other config goes here...
}

Failed to load image because it's violating content security policy

In chrome app I am trying to load images from external link but getting error
Refused to load the image
'unsafe:https://www.google.co.in/images/srpr/logo11w.png' because it
violates the following Content Security Policy directive: "img-src
'self' blob: filesystem: data: chrome-extension-resource:
I already added content_security_policy in manifest.json file
"content_security_policy": "img-src 'self' https://www.google.co.in/ blob: filesystem: data: chrome-extension-resource:;"
and
also explicitly added URL protocols to Angular's whitelist using a regular expression
.config(['$compileProvider',
function ($compileProvider) {
var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0, -1)
+ '|chrome-extension:'
+ currentImgSrcSanitizationWhitelist.toString().slice(-1);
console.log("Changing imgSrcSanitizationWhiteList from " + currentImgSrcSanitizationWhitelist + " to " + newImgSrcSanitizationWhiteList);
$compileProvider.imgSrcSanitizationWhitelist(newImgSrcSanitizationWhiteList);
}
]);
but still error is there.
You cannot override CSP for Chrome Apps (that key is only for extensions).
You will need to adapt your App to fetch then locally cache the images - you can't embed them directly. See Google's guide on Referencing external resources.
Also, take another look at this question - if you're getting unsafe: in your URLs you aren't doing it correctly.

Angular karma-jasmine: Included file cannot be found by XHR/GET

I have included an existing project file in my karma.conf.js files array:
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js',
'bower.json',
'app/data/file.json',
],
I know the file has been matched because I do not get a warning that
WARN [watcher]: Pattern <pattern> does not match any file. I changed that line to a known non-existent file and back to double check.
My base path is the project root:
basePath : '../',
When Angular's controllersSpec.js runs, I use an XHR GET to synchronously load the file, but I get a HTTP 404. Where is the file?
//Synchronously GET the test data
var req = new XMLHttpRequest();
req.open('GET', 'app/data/file.json', false);
req.send(null);
var testData = JSON.parse(req.responseText);
Then, in the test shell, I see:
WARN [web-server]: 404: /app/data/file.json
<user agent> ERROR
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
at <path to project>/test/unit/controllersSpec.js:12
It looks to me like you're trying to load a local file with a GET request; depending on what port or host your server is running on, it may not be able to load it up via a relative path. Try instead pointing it to the full URL path including protocol and domain name, e.g.:
//Synchronously GET the test data
var req = new XMLHttpRequest();
req.open('GET', 'http://servername.com/app/data/file.json', false);
req.send(null);
var testData = JSON.parse(req.responseText);

X-Appengine-Inbound-Appid header not set

I have two AppEngine modules, a default module running Python and "java" module running Java. I'm accessing the Java module from the default module using urlfetch. According to the AppEngine docs (cloud.google.com/appengine/docs/java/appidentity), I can verify in the Java module that the request originates from a module in the same app by checking the X-Appengine-Inbound-Appid header.
However, this header is not being set (in a production deployment). I use urlfetch in the Python module as follows:
hostname = modules.get_hostname(module="java")
hostname = hostname.replace('.', '-dot-', 2)
url = "http://%s/%s" % (hostname, "_ah/api/...")
result = urlfetch.fetch(url=url, follow_redirects=False, method=urlfetch.GET)
Note that I'm using the notation:
<version>-dot-<module>-dot-<app>.appspot.com
rather than the notation:
<version>.<module>.<app>.appspot.com
which for some reason results in a 404 response.
In the Java module I'm running a servlet filter which looks at all the request headers as follows:
Enumeration<String> headerNames = httpRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = httpRequest.getHeader(headerName);
mLog.info("Header: " + headerName + " = " + headerValue);
}
AppEngine does set some headers, e.g. X-AppEngine-Country. But the X-Appengine-Inbound-Appid header is not set.
Why am I'm not seeing the documented behaviour? Any suggestions would be much appreciated.
Have a look at what I've been answered on Google groups, which led to an issue opened on the public issue tracker.
As suggested in the answer I received you can follow, for any update, the issue over there.

Resources