0

i work on my login page for react website with axios i get axios erreur 404 so i decide to check with postman .when i test http resquet with the url i get status 200 ok while i test with post data i get status 404 there is the link of the code https://www.useblackbox.io/editor?id=6a273232-948c-4b4f-84a4-e53c978a66c5

i try to check if my url is wrong or not , so far not . i get that in the console

AxiosError code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 404" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response : {data: '', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …} stack : "AxiosError: Request failed with status code 404\n at settle (http://localhost:5173/node_modules/.vite/deps/axios.js?v=55c2aff0:1206:12)\n at XMLHttpRequest.onloadend (http://localhost:5173/node_modules/.vite/deps/axios.js?v=55c2aff0:1423:7)" [[Prototype]] : Error

1 Answer 1

0

I think the reason is the CORS issue. OR 404 Not Found

You can test by Chrome Dev tool with this demo codes.

I will demo back-end(server.js) and front-end with React Login component.

CORS testing

You can test add or remove server code

app.use(cors()); // For cross-origin resource sharing

Server Demo code

Save as 'server.js'

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Middlewares
app.use(cors()); // For cross-origin resource sharing
app.use(bodyParser.json()); // For parsing JSON in request body

// Mock user for demonstration
const mockUser = {
    email: '[email protected]',
    password: 'password123'
};

// Login endpoint
app.post('/login', (req, res) => {
    const { email, password } = req.body;

    if (email === mockUser.email && password === mockUser.password) {
        res.status(200).json({ message: 'Login successful' });
    } else {
        res.status(401).json({ message: 'Invalid credentials' });
    }
});


// Server listening
const PORT = process.env.PORT || 5173;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

React Login component

import React, { useState } from "react";
import axios from 'axios';

export default function Login() {
    const [email, setEmail] = useState('[email protected]')
    const [password, setPassword] = useState('password123')
    const [message, setMessage] = useState(null); // Initialize with null

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            const response = await axios.post('http://localhost:5173/login', { email, password });
            setMessage(response.data.message);
        } catch (error) {
            // Check if response is available in the error object
            if (error.response) {
                // Display error message and status code
                setMessage(`Error: ${error.response.data.message || ''}, Status Code: ${error.response.status}`);
            } else {
                // Handle other errors like network errors
                setMessage('An error occurred');
            }
        }
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <div>
                    <label htmlFor="email">Email</label>
                    <input type="email" name="email" value={email} onChange={(e) => setEmail(e.target.value)} />
                </div>
                <div>
                    <label htmlFor="password">Password</label>
                    <input type="password" name="password" value={password} onChange={(e) => setPassword(e.target.value)} />
                </div>
                <button type="submit">Log in</button>
            </form>
            {message && <p>{message}</p>}
        </div>
    );
}

Opening DevTools

#1 Open DevTools: In Google Chrome, you can open DevTools by right-clicking anywhere on your web page and selecting "Inspect". Alternatively, you can use the shortcut Ctrl + Shift + I (or Cmd + Option + I on Mac).

Navigate to the Network Tab: In the DevTools window, you'll see a series of tabs like Elements, Console, Sources, and Network. Click on the "Network" tab.

#2 Using the Network Tab Prepare to Capture Data: Make sure the Network tab is open before you trigger the network request (e.g., before you click the "Log In" button in your application). The Network tab needs to be open to record network activity.

Perform the Action: Go back to your application and perform the action that triggers the network request (like submitting the login form).

View Network Activity: After performing the action, you should see a list of network requests in the Network tab of DevTools. Look for your specific request (in this case, it might be labeled as "login" or similar, depending on your API endpoint).

Inspect the Request: Click on the request you're interested in. This will open a side panel with more details.

#3 Analyzing the Request Details General Information: At the top of the side panel, you'll see general information including the Request URL and Request Method (e.g., POST).

Status Code: Under the general information, there's a section for the status code. For example, "Status Code: 200 OK" indicates a successful request, while "Status Code: 404 Not Found" indicates that the requested resource could not be found.

Response: You can also view the response from the server in this panel. Click on the "Response" tab within the side panel to see what data was returned by the server.

Request Headers and Payload: You can inspect the headers and payload (body) of your request. This is useful to confirm if the correct data is being sent to the server.

#1 Successful login Testing

if correct username/password and server support cors()

enter image description here

#2 An error occurred Testing by no CORS

even if correct username/password but server removed cors()

// app.use(cors()); // comment out not supporting cors()

enter image description here

#3 "404" Not Found Testing

In "Login" component change the wrong URL for POST call.

const response = await axios.post('http://localhost:5173/other_login', { email, password });

it will take long time value in DevTool

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Request URL: localhost:5173/login Request Method: POST Status Code: 404 Not Found Remote Address: [::1]:5173 Referrer Policy: strict-origin-when-cross-origin i try your method and i find that
So 404 means your client call URL is not matched with server serving end point URL.
what i should do to made matched
Can you attach your succeed Postman image? Which include URL, header, Body and Status information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.