Unexpected token 'export' error messsage on JavaScript project - javascript

I was trying to copy a JavaScript code that I wrote on a online learning platform.
The code was 2 JavaScript files: Export and Import files.
updated: I tried adding to index.html: type = "module" to both JavaScript files
When I am running the src files now on VS code and using live server. It gives me some error messages on Chrome:
Failed to load resource: the server responded with a status of 404 (Not Found) airplane:1
When not on live server - Open index.html on chrome gives me the following error messages:
Access to script at 'file:///C:/web%20development/studies/frontend/js/test/src/missionControl.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
missionControl.js:1
Failed to load resource: net::ERR_FAILED
index.html:1 Access to script at 'file:///C:/web%20development/studies/frontend/js/test/src/airplane.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
airplane.js:1 Failed to load resource: net::ERR_FAILED
html code
<body>
<script type = "module" src="./src/missionControl.js"></script>
<script type = "module" src="./src/airplane.js"></script>
</body>
</html>
airplane.js
export let availableAirplanes = [
{name: 'AeroJet',
fuelCapacity: 800,
availableStaff: ['pilots', 'flightAttendants', 'engineers', 'medicalAssistance', 'sensorOperators'],
maxSpeed: 1200,
minSpeed: 300
},
{name: 'SkyJet',
fuelCapacity: 500,
availableStaff: ['pilots', 'flightAttendants'],
maxSpeed: 800,
minSpeed: 200
}
];
export let flightRequirements = {
requiredStaff: 4,
requiredSpeedRange: 700
};
export function meetsStaffRequirements(availableStaff, requiredStaff) {
if (availableStaff.length >= requiredStaff) {
return true;
} else {
return false;
}
};
export function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
let range = maxSpeed - minSpeed;
if (range > requiredSpeedRange) {
return true;
} else {
return false;
}
};
export default meetsSpeedRangeRequirements;
missionControl.js
import{ availableAirplanes, flightRequirements, meetsStaffRequirements } from './airplane';
import meetsSpeedRangeRequirements from './airplane';
function displayFuelCapacity() {
availableAirplanes.forEach(function(element) {
console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity);
});
}
displayFuelCapacity();
function displayStaffStatus() {
aircavailableAirplanesrafts.forEach(function(element) {
console.log(element.name + ' meets staff requirements: ' + meetsStaffRequirements(element.availableStaff, flightRequirements.requiredStaff) );
});
}
displayStaffStatus();
function displaySpeedRangeStatus() {
availableAirplanes.forEach(function(element) {
console.log(element.name + ' meets speed range requirements:' + meetsSpeedRangeRequirements(element.maxSpeed, element.minSpeed, flightRequirements.requiredSpeedRange));
});
}
displaySpeedRangeStatus();

Related

JSON post request shows 405 not allowed error (using XMLHttpRequest())

here's my js code:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
Function here is called on a button click
and here's my JSON code:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
I am getting this error when I try to post:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
Please help. I have tried many things already available online but nothing seems to work
The 405 Method Not Allowed Error occurs when the web server is configured so that you cannot perform a specific action for a specific URL. It is an HTTP response status code that indicates that the request method is known to the server, but is not supported by the target resource.

Serverless CORS preflight request failed - AWS API Stripe

I have spent about 2 weeks trying to debug this but no luck.
I have created a lambda function using python that creates a charge. This works fine with Stripe Checkout's simple script. It invokes it and returns the response without any issues (Python).
try:
stripe.api_key = "*******PRIVATE KEY***********"
Tokenstring = event.get('body')
Stripe_List = Tokenstring.split('=')
Token = Stripe_List[1].split('&')[0]
Email = Stripe_List[-1]
Email = Email.replace('%40', '#')
charge = stripe.Charge.create(
amount=100,
currency="gbp",
description="Example charge",
source=Token,
receipt_email=Email
)
print('Full SUCCESSFUL Transaxn Info ==== {}'.format(event))
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success"
}
}
This is invoked very simply in the html body with <form action="https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta" method="POST">
Now, when I try to use the custom stripe checkout code, I get:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
My javascript code is:
var handler = StripeCheckout.configure({
key: '*****PRIVATE KEY*****',
image: 'logo.png',
locale: 'auto',
token: function(token) {
var xhr = new XMLHttpRequest();
xhr.open("POST","https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta", true);
xhr.setRequestHeader('Content-Type','application/json');
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
xhr.onreadystatechange = handler;
xhr.send(JSON.stringify({
body : token
}));
}
});
I have set up OPTIONS in Amazon's API Gateway to respond and have enabled CORS on amazon API gateway.
How can I pass the pre-flight request and let lambda execute the function?
Aside from enabling CORS on the API Gateway Console, your Lambda function itself has to return those CORS headers.
return {
"statusCode": 302,
"headers": {
"Location": "https://example.com/#success",
"Access-Control-Allow-Origin": "*",
}
}

Angular fetch vine thumbnail

I attempt to fetch vine thumbnail following their doc with the following code:
<!-- language: lang-js -->
var onGetVineThumbnailSuccess = function( videoUrl ) {
return function( response ) {
var args = { videoUrl: videoUrl };
args.thumbnailUrl = response['thumbnail_url']; // jshint ignore:line
$rootScope.$broadcast( 'event:onGetVineThumbnailSuccess', args);
};
};
var getVineThumbnail = function ( videoUrl ) {
$http
.get( 'https://vine.co/oembed.json?url=' + encodeURIComponent( videoUrl ) )
.then( onGetVineThumbnailSuccess( videoUrl ) );
};
but in the console I've this error:
XMLHttpRequest cannot load https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2FeV1mMuab7Mp. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
By the way this link: https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2FeV1mMuab7Mp works. If I put directly to browser's url bar. I obtain this JSON:
{
"version": 1.0,
"type": "video",
"cache_age": 3153600000,
"provider_name": "Vine",
"provider_url": "https://vine.co/",
"author_name": "Evengelia",
"author_url": "https://vine.co/u/1204040590484971520",
"title": "Everything was beautiful on this day. #6secondsofcalm",
"thumbnail_url": "https://v.cdn.vine.co/r/videos/59734161E81269170683200901120_45a46e319ea.1.1.8399287741149600271.mp4.jpg?versionId=tc3t.oqGtjpJNlOX1AeM1CAnWONhbRbQ",
"thumbnail_width": 480,
"thumbnail_height": 480,
"html": "<iframe class=\"vine-embed\" src=\"https://vine.co/v/eV1mMuab7Mp/embed/simple\" width=\"600\" height=\"600\" frameborder=\"0\"><\/iframe><script async src=\"//platform.vine.co/static/scripts/embed.js\"><\/script>",
"width": 600,
"height": 600
}
Sounds as CORS issue. But as I've no control on Vine, how should I call this service?
Access-Control-Allow-Origin is set on the response from server, not on client request to allow clients from different origins to have access to the response.
In your case, http://www.vine.co/ does not allow your origin to have access to the response. Therefore you cannot read it.
For more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
But, The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.
The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

how to add a basic keen.io event with javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.
Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).
if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".
if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:
ReferenceError: Keen is not defined
var keenClient = new Keen({
If I download the js file and serve it locally, after the button is clicked, I get the following error response:
Error: Request failed
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
All of these attempts work from Chrome, but I need this to work from other browsers too.
I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.
After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io
So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.
We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.
error.html
<html>
<head>
<title>Error</title>
<script src="/js/vendor/jquery-1.11.2.min.js"></script>
<script src="/js/notification.js"></script>
<script type="text/javascript">
$(document).on('ready', function () {
try {
$.get(document.URL).complete(function (xhr, textStatus) {
var code = xhr.status;
if (code == 200) {
var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
code = codeFromPath;
}
}
Notification.send(code);
});
}
catch (error) {
Notification.send('error.html', error);
}
});
</script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>
notification.js
var Notification = (function () {
var endpoint = 'http://my-rails-server-com/notice';
function send(type, jsData) {
try {
if (jsData == undefined) {
jsData = {};
}
$.post(endpoint, clientData(type, jsData));
}
catch (error) {
}
}
// private
function clientData(type, jsData) {
return {
data: {
type: type,
jsErrorData: jsData,
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
status: status,
navigator: {
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
cookieEnabled: navigator.cookieEnabled,
language: navigator.language,
onLine: navigator.onLine,
platform: navigator.platform,
product: navigator.product,
userAgent: navigator.userAgent
},
history: {
length: history.length
},
document: {
documentMode: document.documentMode,
documentURI: document.documentURI,
domain: document.domain,
referrer: document.referrer,
title: document.title,
URL: document.URL
},
screen: {
width: screen.width,
height: screen.height,
availWidth: screen.availWidth,
availHeight: screen.availHeight,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth
},
location: {
hash: window.location.hash,
host: window.location.host,
hostname: window.location.hostname,
href: window.location.href,
origin: window.location.origin,
pathname: window.location.pathname,
port: window.location.port,
protocol: window.location.protocol,
search: window.location.search
}
}
}
}
return {
send: send
}
}());
example of sending notification manually from js code:
try {
// some code that may produce an error
}
catch (error) {
Notification.send('name of keen collection', error);
}
rails
# gemfile
gem 'keen'
#routes
resource :notice, only: :create
#controller
class NoticesController < ApplicationController
def create
# response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
# that we can use later to easily track down the exact notification on keen
data = params['data'].merge('id' => Time.now.to_i)
Keen.publish(data['type'], data) unless dev?(data)
# we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
render json: nil, status: :ok
end
private
def dev?(data)
%w(site local).include?(data['location']['origin'].split('.').last)
end
end

Refused to execute script from '*'

At https://rawgit.com/UserName/master/file.json (dummy URL) I am hosting a JSON file.
The exact JSON file being hosted it this:
[
{
"name":"Europe",
"id":1
},
{
"name":"USA",
"id":2
}
]
And when I try to obtain this via AngularJS:
return{
fetchData : function(remoteDataId){
var deferred = $q.defer();
var url = 'https://cdn.rawgit.com/Username/master/' + remoteDataId;
$http.get(url, { cache:true }).then
(
function(resp){
deferred.resolve(resp.data)
},
function(err){
deferred.reject();
}
)
return deferred.promise;
}
};
I get this error : Refused to execute script from 'https://rawgit.com/UserName/master/file.json?callback=angular.callbacks._3' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
What is wrong here? According to JSLint my JSON is valid. Should I add anything to the .json file?
I changed $http.jsonp() to $http.get(). It works even though it is a cross origin request.

Categories

Resources