When I try to load my html page i get this error:
Uncaught (in promise) ReferenceError: axios is not defined at get (index.js:7)
When I import it as import axios from 'axios';
i get:
Uncaught SyntaxError: Cannot use import statement outside a module
So either way it's not working properly. I have used npm install axios
too and mentioned the source in the html file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.23.0/axios.js"></script>
or
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
I just don't notice what I could have done wrong. Here's the script sample as it follows:
const apiUrl = 'http://localhost:8000/api/';
async function get(url) {
return (await axios(url)).data;
}
async function loadTable() {
let data = await get(apiUrl 'getList');
let tableDiv = document.getElementById('tableData');
// and so on
I got the api running OK, the only problem is this axio reference. The node script is running fine in another .js file, also Postman can identify it with no problem. Same port, same URL.
CodePudding user response:
If this is a HTML page, like one you would open in your browser, npm
won't be able to add Axios into the page for you. You can consider Node.js code as server-side and your browser as client-side (note this isn't always the case, but it is here).
Also note, import
is meant for Node.js code, and will not work in HTML code without an additional framework, which I assume you are not using here.
Your script
tags are correctly, but they are probably not bring added to your HTML file at the right point. You can use either of these configurations, and it should work:
Script is importing before the elements of the page are created:
<head>
...
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...
</head>
<body>
...
<script src="yourCustomCode"></script>
<body>
Script is importing after the elements of the page are created:
<head>
...
</head>
<body>
...
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="yourCustomCode"></script>
<body>
Either way, just ensure the Axios package is higher up then the code you want to run with Axios.
CodePudding user response:
Axios is an instance from Axios class so you must get method "get" instead of axios(get( ...
Then I recommend to you had use:
axios.get(url)