Access to script blocked by CORS policy - javascript

I am making a simple test project including 2 JavaScript files , where i export and import modules , as shown below .
However ,when opening html page , an error generated in the console shows that :
Access to script at 'file:///C:/Users/index2.js' from origin 'null' has been blocked by CORS policy
Failed to load resource: net::ERR_FAILED (index2.js:1)
I tried to desactivate CORS but that leads always to the same error , i am using Google Chrome browser .
what is abnormal in code and what to do to resolve this problem ?
index2.js :
export default class test {
static method () {
return ('hello world' ) ;
}
index.js :
import test from './index2.js';
console.log (test.method()) ;
in index.html :
<script type = "module" src="./index.js"></script>

I resolved the problem by setting up a local webserver , I Used XAMPP , the link below shows the installation and usage :
https://www.maketecheasier.com/setup-local-web-server-all-platforms/

Related

Display data on the browser console with vue-axios

I have a .json file which I need to display its data on the browser console. I'm working with Vue.js and using vue-axios to fetch data from the .json file.
Here is the code I have on the script tag to do so:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script>
import countries from "./charts/countries.vue";
import axios from "axios";
//const http = axios.create();
export default {
components: {
countries
//languagues
},
mounted() {
axios
.get("./MOCK_DATA.json")
.then(Response => window.console.log(Response.data));
}
};
</script>
I've tried axios.get(...) and I've also tried setting a variable http, which is commented above "export default" and using it, instead of "axios.get(...)". I keep getting these same errors on the browser console:
Failed to load resource: the server responded with a status of 404 (Not Found) :8080/MOCK_DATA.json:1
createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js?2d83:16)
at settle (settle.js?467f:17)
at XMLHttpRequest.handleLoad (xhr.js?b50d:61)
P.S.: The file in which I'm working is App.vue and it's on the "src" folder as well as the "MOCK_DATA.json" file which leads me to believe it's not a path error.
You just need to move your file to public dir, where index.html is and do this request:
axios
.get("/MOCK_DATA.json") //Without dot
.then(Response => window.console.log(Response.data));
It's because Vue dev server looks for files in those dir.

ipyauth with jupyter: google callback results in MIME type mismatch

I am trying to get ipyauth running inside a jupyter notebook as described here. However when clicking on the 'Sign In' button, no pop-up appears. Instead the callback runs into MIME type conflicts.
Two weeks ago, I have been able to run this demo notebook, but a (not related) problem forced me to reinstall ipyauth, and now I run into this issue. I have set up a new Anaconda3 environment and installed ipyauth as described in this tutorial. My jupyter notebook version is 5.7.6 and all necessary extensions are enabled, as listed in the dev-install section.
Opening a console shows the following error, after clicking on the 'Sign In' button:
Script from http://localhost:8888/callback/assets/util.js was blocked due to mime type mismatch
In Firefox the console also states the conflict is due to "text/html". The lines given in the console before the MIME mismatch are:
btn_main clicked widget_box.js:84:20
start startAuthFlow widget_auth.js:38:4
name=google, isIframeMode=true widget_auth.js:46:4
paramsModel widget_util.js:4:4
{"name":"google","url_params":{"response_type":"token","client_id":"729266704353-i9eueh2db24if69v2ohj4brfa94c48ns.apps.googleusercontent.com","redirect_uri":"http://localhost:8888/callback/","scope":"profile openid","include_granted_scopes":"false"}} widget_util.js:5:4
paramsFull widget_util.js:4:4
{"name":"google","authorize_endpoint":"https://accounts.google.com/o/oauth2/v2/auth","url_params":{"response_type":"token","redirect_uri":"http://localhost:8888/callback/","client_id":"729266704353-i9eueh2db24if69v2ohj4brfa94c48ns.apps.googleusercontent.com","scope":"profile openid","access_type":"online","state":"google,iframe,fbixswbono","include_granted_scopes":"false","prompt":"none"},"scope_separator":" ","isJWT":false} widget_util.js:5:4
authUrl widget_util.js:4:4
"https://accounts.google.com/o/oauth2/v2/auth?response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback%2F&client_id=729266704353-i9eueh2db24if69v2ohj4brfa94c48ns.apps.googleusercontent.com&scope=profile%20openid&access_type=online&state=google%2Ciframe%2Cfbixswbono&include_granted_scopes=false&prompt=none" widget_util.js:5:4
start buidReadMessage widget_auth.js:80:4
----------- startAuthFlowInIframe widget_util.js:4:4
undefined widget_util.js:5:4
Other than that, the notebook does not react to the button click.
Do I have to change something in my jupyter config file? Can I somehow find out where this error is exactly coming from? Is this a bug in ipyauth, or am I doing something completely wrong?
In the current version of ipyauth (0.2.5), the Content-Type header of the assets/util.js and assets/main.js files are not set.
A fix for this is to follow the Dev Install section of the docs, installing all necessary extensions, but before you run jupyter notebook to open the notebook interface, change ipyauth/ipyauth/ipyauth_callback/server_extension.py to
import os
import mimetypes
from notebook.base.handlers import IPythonHandler
from notebook.utils import url_path_join
def load_jupyter_server_extension(nb_app):
web_app = nb_app.web_app
web_app.settings['jinja2_env'].loader.searchpath += [
os.path.join(os.path.dirname(__file__), 'templates'),
os.path.join(os.path.dirname(__file__), 'templates', 'assets'),
]
class CallbackHandler(IPythonHandler):
"""
"""
def get(self, path):
"""
"""
nb_app.log.info("in CallbackHandler with path={}".format(path))
self.write(self.render_template('index.html'))
class CallbackAssetsHandler(IPythonHandler):
"""
"""
def get(self, path):
"""
"""
nb_app.log.info("in CallbackAssetsHandler with path={}".format(path))
mime_type, _ = mimetypes.guess_type(path)
self.set_header('Content-Type', mime_type)
self.write(self.render_template(path))
host_pattern = '.*$'
base_url = web_app.settings['base_url']
web_app.add_handlers(
host_pattern,
[(url_path_join(base_url, '/callback/assets/(.*)'), CallbackAssetsHandler),
(url_path_join(base_url, '/assets/(.*)'), CallbackAssetsHandler),
(url_path_join(base_url, '/callback(.*)'), CallbackHandler),
(url_path_join(base_url, '/callback.html(.*)'), CallbackHandler),
]
)
nb_app.log.info("ipyauth callback server extension enabled")
This adds the correct Content-Type to those two javascript files.
I'll open an issue on the ipyauth repo regarding this problem. Hopefully a more robust solution will be added to the master branch soon so we can use this tool in production

How to remove this error 'No application configured for scope type 'websocket''

I am trying to build a chat app with Django but when I try to run it I get this error
No application configured for scope type 'websocket'
my routing.py file is
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter , URLRouter
import chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket':AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
my settings.py is
ASGI_APPLICATION = 'mychat.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
when I open my URL in 2 tabs I should be able to see the messages that I posted in the first tab appeared in the 2nd tab but I am getting an error
[Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
/home/vaibhav/.local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2801:processHandshake
/home/vaibhav/.local/lib/python3.6/site-packages/txaio/tx.py:429:as_future
/home/vaibhav/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred
/home/vaibhav/.local/lib/python3.6/site-packages/daphne/ws_protocol.py:82:onConnect
--- <exception caught here> ---
/home/vaibhav/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred
/home/vaibhav/.local/lib/python3.6/site-packages/daphne/server.py:198:create_application
/home/vaibhav/.local/lib/python3.6/site-packages/channels/staticfiles.py:41:__call__
/home/vaibhav/.local/lib/python3.6/site-packages/channels/routing.py:61:__call__
]
WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:34724]
I couldn't find a duplicate of this question on stackoverflow
problem could be in the asgi.py :
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
# Just HTTP for now. (We can add other protocols later.)
})
Those using centos,My issue was with redis. My system had redis version 3 updating it to redis version 6 or above got my django channels working. Redis was breaking in the background. Hope it helps

Working with JavaScript module

I read this and this, and wrote the below files:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="module">
(async () => {
const moduleSpecifier = './lib.mjs';
const {_default, repeat, shout} = await import(moduleSpecifier);
repeat('hello');
// → 'hello hello'
document.getElementById("demo").innerHTML = shout('Dynamic import in action');
// → 'DYNAMIC IMPORT IN ACTION!'
})();
</script>
</head>
<body>
<h1>This is a Heading</h1>
<p id="demo">Loading ..</p>
</body>
</html>
lib.mjs:
export const repeat = (string) => `${string} ${string}`;
export function shout(string) {
return `${string.toUpperCase()}!`;
}
But once trying it at chrome, I got the below:
Access to Script at 'file:///Users/hasan/Documents/mjs/lib.mjs' from
origin 'null' has been blocked by CORS policy: Invalid response.
Origin 'null' is therefore not allowed access.
In nodejs I can add the below line, but can I do it to my file, knowing that it is not running from server!
response.setHeader('Access-Control-Allow-Origin', '*');
UPDATE
I tried running it from this server, and set the CORS, but got the below error:
Failed to load module script: The server responded with a
non-JavaScript MIME type of "". Strict MIME type checking is enforced
for module scripts per HTML spec.
UPDATE 2
It worked with me when I renamed the .mjs to .js, is this means the .mjs not yet supported!!
The first error output is because JavaScript modules are fetched with CORS, and I guess you did not use a server that set up the proper headers as explained in this article: https://developers.google.com/web/fundamentals/primers/modules
In your second attempt with 200 OK Web Server extension for Chrome, it does not yet support JavaScript modules because of lacking MIME type support. There are an issue for this on the developers' Github https://github.com/kzahel/web-server-chrome/issues/133

Cannot load modules with traceur - tries to access file via xhr

I am trying to use traceur. When I want to load a module though, I get an error that it was unsuccessful. My code is based on the example traceur provided in its documentation on modules.
Here is the main.html:
<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
<script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
<script>
System.traceurOptions = { experimental: true }
</script>
<script type="module" src="ProfileView.js"></script>
And the loaded module:
// ProfileView.js
import {firstName, lastName, year} from './Profile.js';
function setHeader(element) {
element.textContent = firstName + ' ' + lastName;
}
// rest of module
// Profile.js
export var firstName = 'David';
export var lastName = 'Belle';
export var year = 1973;
I get the following error in Chrome:
XMLHttpRequest cannot load
file:///C:/Code/Tests/Traceur/ProfileView.js. Cross origin requests
are only supported for protocol schemes: http, data, chrome,
chrome-extension, https, chrome-extension-resource.
WebPageTranscoder FAILED to load
file:///C:/Code/Tests/Traceur/ProfileView.js
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest':
Failed to load 'file:///C:/Code/Tests/Traceur/ProfileView.js'.
I know that you cant make xhr-requests via the file system but I have seen some tutorials in which the code is structured similarly to mine and it works there...
What may I be doing wrong?
You cannot access the file system with xhr, you should open those pages over http by running a local webserver. If you really want to enable file system access you can: http://www.chrome-allow-file-access-from-file.com/
I.e. you start chrome chrome.exe --allow-file-access-from-files

Categories