Folder Structure(Backend)
The updated dependencies in package.json file will look like:
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"nodemon": "^3.1.0"
}
Step 3: Open index.js file and write the following code to create a server.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(cors()); // Add this line to enable CORS
// Endpoint to receive username and password
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'password') {
res.status(200).json({ message: 'Login successful' });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 4: Run the server by running the following command in the terminal
node index.js
How to send Basic Auth with Axios in React & Node ?
Basic Auth is a simple authentication scheme. It involves sending a username and password with each request to the server through HTTP. Axios is a popular HTTP client for making requests in JavaScript.
In this article, we will create a React App to demonstrate sending basic Auth with Axios and discuss the following approaches:
Table of Content
- Basic approach with Inline Header
- Creating an Instance of Axios
Contact Us