Angularjs Error in loading external jsonfile from server - javascript

I am trying to load json file from server .Here is my services.js file
angular.module('starter.services', [])
/**
* A simple example service that returns some data.
*/
.factory('Friends', function($http) {
var friends;
//here is the code for server access
$http.get('http://wwww.root5solutions.com/ionictest/get.json').then(function(msg){
console.log("console output"+msg.data);
friends=msg.data;
console.log("from server"+friends.data);
});
return {
all: function() {
return friends;
},
get: function(friendId) {
return friends[friendId];
}
}
});
But its not worked properly.Here is my console message
XMLHttpRequest cannot load http://www.root5solutions.com/ionictest/get.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I have also faced the same problem.I am sure it will resolve your problem,
For Windows... create a Chrome shortcut on your desktop > Right-clic > properties > Shortcut > Edit "target" path : > "C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
NOTE: After setting this exit from chrome and then open

you have to whitelist that URL
try this
.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our other assets domain. Note there is a difference between * and **.
'http://wwww.root5solutions.com/ionictest/**',
]);
})

All this problem beacuse i tested only using browser.When tesing on device/emulator its working perfect.There is no need of additional coding to overcome this problem.

Related

Can't remove CORS error even so I included all headers

I am writing simple web-site with js-client and a server side(python) I did everything to remove CORS error but nothing works. I wrote all needed headers for this but still get this error. So web-site should send a request to a server and get answer.
Error:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
myFile.html:
<!DOCTYPE html>
<html>
<head>
<title>requestJs</title>
</head>
<body>
<button class="myButton">SEND</button>
<script type="text/javascript">
let theButton = document.querySelector(".myButton");
theButton.addEventListener('click',function() {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
alert(`Статус: ${xhr.status}; Результат: ${xhr.response}`)
};
xhr.onerror = function() {
alert('Ошибка запроса');
};
xhr.open("GET", "http://127.0.0.1:8000/", true);
xhr.send(2);
})
</script>
</body>
</html>
Server side:
import http.server as httpserver
class CORSHTTPRequestHandler(httpserver.SimpleHTTPRequestHandler):
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.html":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Access-Control-Allow-Origin:", "*")
self.send_header("Access-Control-Allow-Methods:", "GET,HEAD,PUT,PATCH,POST,DELETE")
self.send_header("Access-Control-Allow-Headers:", "Content-Type, Access-Control-Allow-Origin, xxx")
self.end_headers()
return f
if __name__ == "__main__":
import os
import socketserver
import sys
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
handler = CORSHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print(f"serving at port {PORT}")
httpd.serve_forever()
Help me please, what is my problem?
This is not a comprehensive answer but it might help.
CORS is entirely a browser feature. You can turn it off in your browser. I suggest the first step therefore is to launch a CORS-free browser to test your app. Make sure not to open your banking page in this browser session though, it isn't safe!
google-chrome --user-data-dir=/var/tmp/Chrome --disable-web-security
If everything works then then issue is just CORS.
If you are only running in a dev environment, you can just do this everytime even.
If you are running in production, the easiest option is often just to use a gateway that fixes this stuff for you. That's how I got mine working.
If the above isn't good enough and you want to debug, remember that all browser CORS requests are initiated by a preflight OPTIONS requests. Sometimes that's where the problem comes in. Make sure your server is able to handle and respond to OPTIONS, and check that it is responding correctly.

HMS AnalyticsKit Demo for Javascript cannot reach server

Here is what I did:
Cloned HMS AnalyticsKit Demo for Javascript - https://github.com/HMS-Core/hms-analytics-demo-javascript.git in Germany Frankfurt AWS EC2
cd hms-analytics-demo-javascript/hmsanalyticskitdemo/
npm install
npm run dev
Use Chrome browser and visit http://x.x.x.x:8080 (EC2), complete the quiz and post score
Inspect Console - https://ibb.co/TKDm586. There is no CORS or 401 error.
This is what I find in hms-analytics-demo-javascript/hmsanalyticskitdemo/src/main.js:
var agConnectConfig =
{
"agcgw":{
"backurl": "https://lfagcgwtest01.hwcloudtest.cn:15602",
"url": "https://lfagcgwtest01cn.hwcloudtest.cn:18062"
},
"client":{
"cp_id":"4130086000000637176",
"product_id":"258913027873047688",
"client_id":"401147640282098944",
"client_secret":"ABA91A52EF1FAB651F57AF091CEC149EECAFB01757DF1224FC384D2173828480",
"app_id":"98751101985125555",
"api_key":"CgB6e3x9zs8IL+Frjllsf9DoteK4Taz7jAseM9P+ikVZBJhHu87FpdEpqq0CimpayCrJgUrkUnV2RM86fyFiD4FE"
},
"service":{
"analytics":{
"collector_url":"habackup.hwcloudtest.cn:31405,datacollector-drcn.dt.dbankcloud.cn",
"resource_id":"p1",
"channel_id":""
},
"cloudstorage":{
"storage_url":"https://agc-storage-drcn.platform.dbankcloud.cn"
},
"ml":{
"mlservice_url":"ml-api-drcn.ai.dbankcloud.com,ml-api-drcn.ai.dbankcloud.cn"
}
},
"region":"CN",
"configuration_version":"1.0"
};
Then I change it to my own agconnect-services.json (note that I changed cp_id, product_id, client_id, client_secret, app_id, package_name, api_key. My data storage location is Germany):
var agConnectConfig =
{
"agcgw":{
"backurl":"connect-dre.dbankcloud.cn",
"url":"connect-dre.hispace.hicloud.com"
},
"client":{
"cp_id":"890001000000000000",
"product_id":"736430070000000000",
"client_id":"451560030000000000",
"client_secret":"5950F0F77523D1C95914089A046DED446E09A02036D8AAAAAAAAAAAAAAAAAAAA",
"app_id":"100000000",
"package_name":"com.aaaa.aa.aaaaaaa",
"api_key":"CgB6e3x9LNm1WQuE1uhjpEI6kdQD7xD23LfdkttRcakwi404NmcxlOBVUslatUnb5dJzXXXXXXXXXXXXXXXXXXXX"
},
"service":{
"analytics":{
"collector_url":"datacollector-dre.dt.hicloud.com,datacollector-dre.dt.dbankcloud.cn",
"resource_id":"p1",
"channel_id":""
},
"cloudstorage":{
"storage_url":"https://ops-dre.agcstorage.link"
},
"ml":{
"mlservice_url":"ml-api-dre.ai.dbankcloud.com,ml-api-dre.ai.dbankcloud.cn"
}
},
"region":"DE",
"configuration_version":"1.0"
}
I repeated step 5, I saw CORS errors - https://ibb.co/HHQvMVL
POST https://datacollector-dre.dt.hicloud.com/webv3 net::ERR_FAILED
If I turn on CORS plugin on Chrome, I saw 401 errors - https://ibb.co/9tXMrHS
POST https://datacollector-dre.dt.hicloud.com/webv3 401
I see no analytics in my app > analytics > real-time overview console.
Is there something wrong with my steps? Could this is be API/server issue?
Thanks.
Your integration procedures are correct. The problem is that the latest version of SDK should be integrated.
The earlier version of the JavaScript SDK has an authentication failure issue, which causes the fault to run the demo. You are advised to download the latest SDK 5.0.4.300 which rectified the authentication failure issue, and perform the verification.

ServiceWorker MIME Type Error ('text/html') on register (React)

The current behavior:
Service worker does not register due to the below error
The expected behavior:
Service worker registers
Details
Posted as a github issue:
https://github.com/facebook/create-react-app/issues/8593
Service worker is giving the following error when attempting to register:
Error during service worker registration:
DOMException: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/sw.js'):
The script has an unsupported MIME type ('text/html').
console. # index.js:1
sw.js is showing in the sources tab of the Chrome dev tools, but not registering.
React version: 16.12.0
Error Message:
Error during service worker registration: DOMException:
Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/sw.js'):
The script has an unsupported MIME type ('text/html').
Failed ServiceWorker in Chrome's Inspect Tab:
Steps To Reproduce:
Register a Service Worker in React (change from unregister to register, or place SW code directly in index.html, or use a simpler SW. All cause the same error when running, in either dev or a build react app.)
SW Example:
export function register() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./sw.js")
.then(function(registration) {
// Successful registration
console.log(
"Hooray. Registration successful, scope is:",
registration.scope
);
})
.catch(function(error) {
// Failed registration, service worker won’t be installed
console.log(
"Whoops. Service worker registration failed, error:",
error
);
});
}
}
Also, `http://localhost:3000/sw.js when using the default SW from React returns this HTML:
Using the code sample above returns index.html (default 404, http://localhost:3000/) when trying to access http://localhost:3000/sw.js
Suggested fixes:
Move sw.js to public folder, gives this error:
Is there a way to change the header (from text/html to application/javascript) for specifically sw.js when served to the browser in React?
I tried following some Medium articles on registering custom serviceWorkers in React, to no avail...
When running webpack dev server, it renders default index.html for missing resource.
If you use your browser to load http://localhost:3000/sw.js, you will actually see a rendered react app (started by the index.html). That's why the mime type is html, not javascript.
This fallback to index.html is designed to support SPA with front-end routes. For example /product/123/reviews has no such html file in backend, the JS SPA app takes care of it in front-end.
Why your file is missing? I guess you created that file in the root folder of your project.
Webpack dev server doesn't serve from that root folder.
Move your sw.js into public/ folder of your project, it will be served up as expected.
This may be a duplicate of this one 61776698
Main thing you need to know: Create the serviceWorker inside public folder in order to be treated as .js file and not text/html file.
Then register that service in your index.js
Step 1, create public/sw.js
self.addEventListener('message', async (event) => {
console.log('Got message in the service worker', event);
});
Step 2, create src/sw-register.js
export default function LocalServiceWorkerRegister() {
const swPath = `${process.env.PUBLIC_URL}/sw-build.js`;
if ('serviceWorker' in navigator && process.env.NODE_ENV !== 'production') {
window.addEventListener('load', function () {
navigator.serviceWorker.register(swPath).then(registration => {
console.log('Service worker registered');
});
});
}
}
Step 3, in src/index.js, add these two lines
import LocalServiceWorkerRegister from './sw-register';
...
LocalServiceWorkerRegister();
You can change some things for your needs, but with those changes, you should be able to work with a custom service worker in a create-react-app application
You can write code at server side to handle sw.js file. below is nodejs code which intercept sw.js file request and read from folder and send back to browser.
app.get('/sw.js', (req, res) => {
if (__DEVELOPMENT__) {
http.get('http://localhost:4001/static/build/sw.js', (r) => {
res.set({
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate'
});
r.setEncoding('utf8');
r.pipe(res);
}).on('error', (e) => {
console.error(`Error in sending sw.js in dev mode : ${e.message}`);
});
} else {
res.setHeader('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate');
res.sendFile('sw.js', { root: path.join(__ROOT_DIRECTORY__, 'assets', 'build') }); // eslint-disable-line no-undef
}
});

leaflet maps add raster

i want to add a raster file in the leaflet map,after from searching i find this example where is that i need i think georaster-layer-for-leaflet-example.
the code look simple js :
var parse_georaster = require("georaster");
var GeoRasterLayer = require("georaster-layer-for-leaflet");
// initalize leaflet map
var map = L.map('map').setView([0, 0], 5);
// add OpenStreetMap basemap
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var url_to_geotiff_file = "example_4326.tif";
fetch(url_to_geotiff_file)
.then(response => response.arrayBuffer())
.then(arrayBuffer => {
parse_georaster(arrayBuffer).then(georaster => {
console.log("georaster:", georaster);
/*
GeoRasterLayer is an extension of GridLayer,
which means can use GridLayer options like opacity.
Just make sure to include the georaster option!
http://leafletjs.com/reference-1.2.0.html#gridlayer
*/
var layer = new GeoRasterLayer({
georaster: georaster,
opacity: 0.7
});
layer.addTo(map);
map.fitBounds(layer.getBounds());
});
});
error :
GeoTIFF: Object
bundle.js:16 Fetch API cannot load file:///C:/Users/username/Downloads/georaster-layer-for-leaflet-example-master/example_4326.tif. URL scheme must be "http" or "https" for CORS request.
1.georaster # bundle.js:16
bundle.js:16 Uncaught (in promise) TypeError: Failed to fetch
at Object.1.georaster (bundle.js:16)
at s (bundle.js:1)
at e (bundle.js:1)
at bundle.js:1
any idea how to fix it ?
The error message is saying that the tiff should be hosted online: "URL scheme must be "http" or "https".
Try putting your tiff online somewhere such as on github or the server you plan to host your map, the on the line var url_to_geotiff_file = "example_4326.tif";, use the full URL for the tiff.
Faced the same issue!
Steps to solve the issue:
1) You can solve it by, publishing it on a local web server such as apache tomcat (by default your file URL will be something like: http://localhost:8080/file_name.tif).
2) Now if you will try to load the map georaster layer, you will get an error such as this:
Access to fetch at 'http://localhost:8080/file_name.tif' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
3) To solve the above problem add the extension Allow-Control-Allow-Origin to your chrome browser and enable it.
It will work then!

AngularJS and Web API :- net::ERR_CONNECTION_REFUSED in chrome and error 00002efd in IE

There are lots of question like my question but I didn't any working solution.
I am using AngularJS and WebApi2 in my application.
Here is the JS code which call the initial API.
(function (module) {
var baseUrl= "http://localhost:85";
module.constant('Config', baseUrl);
module.service('identities', ['$http', function ($http) {
var uri = baseUrl+ '/api/controller/GetRole';
var identities = {};
identities.get = function () {
var temp = $http.get(uri);
console.log(temp, "identities");
return temp;
}
return identities;
}]);
This function call the GetRole method in web API controller to retrieve user role.The output of this method is JSON with user details.
I have deployed the application on a server to port 85. When I run the application it's throwing error in Chrome:
net::ERR_CONNECTION_REFUSED
and in IE 11:
XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd
There is no log created in IIS for this request.
Using fiddler I got this in Raw with status code 502 in response.
The connection to 'localhost' failed.
Error: ConnectionRefused (0x274d).
System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:85.
I have also tried by disabling the CORS in chrome but no luck.
IF I use IP address of server instead of localhost as baseUrl in angular JS code then it's working fine.
Why it's not working with localhost?
I am doing a GET call and Error for me is 00002efd not 00002ef3.

Categories

Resources