I'm using axios to make a live laravel project and get this error: Uncaught ReferenceError: axios is not defined.
I already have run the npm install axios --save command even though laravel already comes with axios installed.
I imported app.js in my view component like this:
<script src="{{ asset('js/app.js') }}"></script>
<script>
(function() {
const options = document.querySelectorAll('.quantity')
Array.from(options).forEach(function(element) {
element.addEventListener('change', function() {
const id = element.getAttribute('data-id')
axios.patch(`/cart/${id}`, {
quantity: this.value
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
})
});
})();
I believe the first script tag is causing the issue because I get this error in the console:
GET http://127.0.0.1:8000/js/app.js net::ERR_ABORTED 404 (Not Found)
However, I don't know how to link to app.js file properly.
EDIT: the issue was solved after I ran npm install npm install vite npm run dev and added this line to my view file up in the head tag:
#vite(['resources/css/app.css', 'resources/js/app.js'])
When I try to make a call from my front-end (NextJS) I get the following error Error: Body must be a string. Received: undefined.
I can successfully make a call from my AppSync console, but not from my front-end. I have pushed the following schema.graphql file with amplify push:
type Mutation {
...
cancelCard(input: CancelCardInput!): AWSJSON
#function(name: "myp-service-prod-cancel-stepfunction-lambda")
}
I'm seeing logs in CloudWatch when I trigger the Lambda from the Lambda and AppSync consoles, but something is blocking the calls from my javascript:
import { cancelCard } from "../src/graphql/mutations";
const lambdaResponse = await API.graphql(
graphqlOperation(cancelCard, {
input: { id: cardId },
})
)
The problem was that I had performed amplify codegen configure and updated from javascript to typescript. As a result, Amplify had updated my src/ folder to have .ts files in, but not removed the .js files. This meant that where I had:
src/graphql/
mutations.ts
mutations.js
My app was ignoring the mutations.ts file.
Deleting the js files solved the issue.
Created an instance of the Worker class in which the file is imported, but an error appears on startup in the console "import declarations may only appear at top level of a module"
Code of the worker call file:
const worker = new Worker('./js/workers/calculateRequestData.js', {
type: 'module',
});
worker.postMessage({ data: '1' });
worker.addEventListener('message', (event) => {
console.log(event.data);
});
worker.addEventListener('error', (error) => {
console.error(error.message);
});
Code of the file calculateRequestData.js
import template from '../Template/template.js';
onmessage = function (e) {
console.log(e.data);
postMessage(e.data);
};
In network files come with the status 304 (if it helps)
Tried to do:
import template from '../Template/template.js' assert { type: 'module' }
self.template = require('../js/Template/template.js // Error: require not found (or does not work, something similar)
self.importScripts('../js/Template/template.js') // The error is the same as in the previous paragraph, only about importScripts.
All of this doesn't work either
The error was in using the "standard" import... from '...'
The worker file turns into one file with a script, where there should be no exports and imports (in the usual form for modules). In order to import a file, or several files, you need to use importScripts() in the worker (you can not use the keyword self). importScripts() "expands" the imported file in the worker file.
In the vue cli, the worker files and all its imported files should be stored not in the src directory, but in public. This is due to the fact that they are not compiled into a common bundle, but a request is made to a specific file.
Example of the correct code:
File with a worker call:
const worker = new Worker('./js/workers/calculateRequestData.js');
worker.postMessage({...});
worker.addEventListener('message', (event) =>
console.error(event.data); // handle message
worker.terminate(); // don't forget to delete worker
});
worker.addEventListener('error', (error) => {
console.error(error.message); // handle error
worker.terminate(); // don't forget to delete worker
});
File calculateRequestData.js
self.importScripts('../Template/template.js');
onmessage = function (e) {
template.calculate(...) // work with imported filse
};
I also ran into a problem when the production build did not work due to the incorrect mime-type ('application/octet-stream') of the worker files and the imported script. This is due to the fact that our server by default have files with such a mime-type, while the browser by default calls the "Save as" modal window. This is treated by specifying in the configuration file for mime types by adding the line 'application/octet-stream' The solution was found here - application/octet-stream mime type issue with codeigniter
Example:
'js' => [
'application/x-javascript',
'text/plain',
'application/octet-stream',
],
I'm trying to make a request in a local file, but I don't know when I try to do on my computer show me an error. Is possible make a fetch to a file inside your project?
// Option 1
componentDidMount() {
fetch('./movies.json')
.then(res => res.json())
.then((data) => {
console.log(data)
});
}
error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// Option 2
componentDidMount() {
fetch('./movies.json', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then( res => res.json())
.then((data) => {
console.log(data);
});
}
error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// This works
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then( res => res.json() )
.then( (data) => {
console.log(data)
})
}
Try to place your json file in the public folder like so :
public/movies.json
and then fetch using
fetch('./movies.json')
or
fetch('movies.json')
I have experienced the same problem previously. When I place the json file in the public folder, problem is solved.
When using fetch, React normally reads asset/resources files in the public folder.
You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server. To resolve the issue, you have a few options available to you. I am going to outline the two that are most commonly suggested for such a thing:
Use Node.js and something like expressjs to host your own server that serves the file you want to fetch. While this procedure might require more effort and time, it is certainly more customizable and a good way to learn and understand how fetching from a backend works.
Use something like Chrome Web Server to easily set up a very simple server to serve your file on your local network. Using this method, you have very little control over what you can do with said web server, but you can quickly and easily prototype your web application. However, I doubt there's a way to move this method to production.
Finally, there are other options where you can upload one or more files online and fetch them from an external URL, however this might not be the optimal strategy.
Your JSON file needs to be served by the server so you need the express server (or any other). In this example we are using express.
Note: you can also download git repo
App.js File
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
const myHeaders = new Headers({
"Content-Type": "application/json",
Accept: "application/json"
});
fetch("http://localhost:5000/movie", {
headers: myHeaders,
})
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
console.log(data);
this.setState({ data });
});
}
render() {
return <div className="App">{JSON.stringify(this.state.data)}</div>;
}
}
export default App;
server.js
var express = require("express");
var data = require('./movie.json'); // your json file path
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get("/movie", function(req, res, next) {
res.send(data);
});
app.listen(5000, () => console.log('Example app listening on port 5000!'))
I was encountering the same error and there are two changes I made in my code to get rid of the error. Firstly, you don't need an express server to serve your files you can read data from a local json file inside your public folder in your create-react-app directory.
const getData=()=>{
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])
First, as suggested in some of the answers above ensure that your json file is inside the public folder and the path parameter inside the fetch function is correct as above. Relative paths didn't work for me.
Second, set the headers as shown. Removing the headers part from my fetch call was still giving me this error.
a simple solution to this is to use live server extension (if you use vs code)
Say that i have the following file test.html
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script>
var depdata;
depdata = fetch("test1.geojson")
.then((data) => {
return data;
});
depdata.then(function(data) {console.log(data)})
</script>
</body>
</html>
When access the file in the firefox through file://... I get the following error:
Cross-Origin Request Blocked:....
When I followed the error on firefox I got the following explanation
CORS requests may only use the HTTPS URL scheme, but the URL specified by the request is of a different type. This often occurs if the URL specifies a local file, using a file:/// URL.
To fix this problem, simply make sure you use HTTPS URLs when issuing requests involving CORS, such as XMLHttpRequest, Fetch APIs, Web Fonts (#font-face), and WebGL textures, and XSL stylesheets.
So the as far as I understand we just need to access the test.html through HTTP. The most straight forward way around this problem was the python simple http server. In the terminal.
> cd directory of the project.
> python3 -m http.server 8000 --bind 127.0.0.1
Then in the browser:
http://localhost:8000/test.html
My go-to approach is to use express-generator to set up a quick local server, then run ngrok (free tier is fine) and point your app to the url it creates. This has the advantage of letting you easily test your fetching in the iOS simulator or Android emulator, as well as on a device not tethered to your computer. Plus, you can also send the url to people testing your app. Of course, there would need to be a way for them to manually input that url so the app could set it as the fetch endpoint.
I got it working rather very simple way - no express / webserver really needed. Just do :
import data from '../assets/data.json';
and use the json data like this (say if it is a JsonArray) :
data.map(movie ...
Do this in App.js or some other class extending React.Component,
The error
Unexpected token < in JSON at position 0
comes from the HTML file that is returned if the request is unsuccessful. The first element (at position 0) of an HTML file is typically a '<'. Instead of a JSON, an attempt is made to read in an HTML file.
You can find the returned HTML File in the Inspect Tool -> Network -> Erroneous file marked in red -> Reponse. There you can see what the specific error is. Example Error Message
To fix the error for me, it helped to move the file to be imported to the Public folder of my React project and then import it like this from a file in the 'src' folder: fetch('dataTemplate.json')
You can place your json file in the public folder. In your React component you can use userEffect (). You don't need Express.js for this case.
React.useEffect(() => {
fetch("./views/util/cities.json")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
});
To fetch local files, a good alternative:
npm install file-fetch
to read a file:
const fileFetch = require('file-fetch')
fileFetch('./public/user.json').then((res) => {
res.body.pipe(process.stdout)
})
See doc
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/