Zaman Imran
Zaman Imran

Reputation: 1

Axios is not defined nodeJs

I am using NodeJs for building RFID based Authentication app. However, axios is not defined error occurs.

const http = axios.create({
  headers: {'Cache-Control': 'no-cache'}
});

I have installed the following dependencies for the project. package.JSON

{
  "dependencies": {
    "axios": "^0.21.0",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mqtt": "^4.2.6",
    "mysql": "^2.18.1",
    "promise": "^8.1.0",
    "request": "^2.88.2",
    "request-promise": "^4.2.6"
  }
}

Upvotes: 0

Views: 5169

Answers (4)

Joseph Ukwenya
Joseph Ukwenya

Reputation: 1

First, try installing axios using the npm command below:

npm install axios

Then import it to your app like this:

const axios = require('axios')

Or if you're using import/export modules:

import axios from 'axios';

If it doesn't work, then you might want to try using a cdn like this: https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.4/axios.min.js

Upvotes: 0

Eric Ng
Eric Ng

Reputation: 1

Don't forget to import it in each file

const axios = import('axios');

Upvotes: 0

Stephan Bakkelund Valois
Stephan Bakkelund Valois

Reputation: 1072


once a npm (node) library is installed into your app, you need to require it into the files you want to use it in.

You can require the file in a node.js application like this:

const package = require('package');

So to use axios in your file, you will have to import it the same way:

const axios = require('axios');

If you want to use axios in a client based application, which are run by the browser (React, angular, native js, etc) you'll import files in a similar way, example:

import axios from 'axios';

There are no global imports. You need to explicitly import all the libraries into the file you want to use them in.

Upvotes: 1

Somto
Somto

Reputation: 23

as commented by @Tkol

axios is not defined because you are yet to import it before you needed to use it to create a request. So just make a little change to your code

const axios = require('axios') //add this line, this imports the axios functionalities into your code

const http = axios.create({
  headers: {'Cache-Control': 'no-cache'}
});

Same goes for anything you might be using later, you would have to import an instance of it before using it. Just having in your package.json file isnt enough or installing it via npm

require('name_of_library')

for example for when you would need to use cors, you would do

const cors = require('cors')

Upvotes: 0

Related Questions