OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Title: Spring Boot API Endpoint Returning 404 Not Found for Registration Request (no databases)

  • Thread starter Thread starter Jens Dorrestijn
  • Start date Start date
J

Jens Dorrestijn

Guest
I'm developing a web application deployed on Azure. The registration endpoint of my API is returning a 404 Not Found error when accessed from the frontend. The backend is set up to handle registration requests, and the frontend is correctly configured to send the registration data. this is the java controller it also returns a 404 when deployed on a localhost. (ive checked if the endpoints are correct yes) the end goal for me is so my login works (deployed on azure) and not just localhost if i even get that to work

Code:
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody User newUser) {
        User registeredUser = userService.registerUser(newUser.getPhoneNumber(), newUser.getUsername(), newUser.getPassword());
        if (registeredUser != null) {
            return ResponseEntity.ok("Registration successful");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Registration failed");
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody User loginUser, HttpSession session) {
        User user = userService.loginUser(loginUser.getUsername(), loginUser.getPassword());
        if (user != null) {
            session.setAttribute("userId", user.getUserId());
            Map<String, String> response = new HashMap<>();
            response.put("message", "Login successful");
            return ResponseEntity.ok(response);
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "Invalid credentials");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser(HttpSession session) {
        session.invalidate();
        Map<String, String> response = new HashMap<>();
        response.put("message", "Logged out successfully");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/test")
    public ResponseEntity<String> testEndpoint() {
        return ResponseEntity.ok("Test endpoint is working!");
    }
}

Code:
public class UserService {
    private UserData userData = new UserData();

    public User registerUser(String phoneNumber, String username, String password) {
        return userData.registerUser(phoneNumber, username, password);
    }

    public User getUserById(String userId) {
        return userData.getUserById(userId);
    }

    public User loginUser(String username, String password) {
        return userData.loginUser(username, password);
    }
}

Code:
package Backend;

import java.util.ArrayList;
import java.util.List;

public class User {
    private String userId;
    private String phoneNumber;
    private String username;
    private String password;
    private List<User> friends;

    public User(String userId, String phoneNumber, String username, String password, List<User> friends) {
        this.userId = userId;
        this.phoneNumber = phoneNumber;
        this.username = username;
        this.password = password;
        this.friends = friends;
    }

    // Getters and setters
}

Code:
document.getElementById('registerForm').addEventListener('submit', function(event) {
    event.preventDefault();
    let username = document.getElementById('username').value;
    let password = document.getElementById('password').value;
    let phoneNumber = document.getElementById('phonenumber').value;

    var userData = {
        username: username,
        password: password,
        phoneNumber: phoneNumber
    };

    fetch('http://localhost:8080/api/users/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => {
        if (response.ok) {
            alert('Registration successful!');
            document.getElementById('registerForm').reset();
            window.location.href = 'login.html';
        } else {
            throw new Error('Registration failed.');
        }
    })
    .catch(error => {
        console.error('Registration error:', error);
        alert('Registration failed. Please try again later.');
    });
});

Issue: When I try to submit the registration form, I receive a 404 Not Found error. I have verified that my API is correctly deployed on Azure and should be accessible

I have: Ensured that the Azure app service is running. Verified that the endpoint /api/users/register is correctly defined in UserController.java. Checked the CORS configuration in WebConfig.java to allow requests from all origins. Confirmed that the JavaScript file (Register.js) is correctly linked and making a POST request to the correct Azure URL.
<p>I'm developing a web application deployed on Azure. The registration endpoint of my API is returning a 404 Not Found error when accessed from the frontend. The backend is set up to handle registration requests, and the frontend is correctly configured to send the registration data.
this is the java controller
it also returns a 404 when deployed on a localhost. (ive checked if the endpoints are correct yes)
the end goal for me is so my login works (deployed on azure) and not just localhost if i even get that to work</p>
<pre><code>@RestController
@RequestMapping("/api/users")
public class UserController {

private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}

@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody User newUser) {
User registeredUser = userService.registerUser(newUser.getPhoneNumber(), newUser.getUsername(), newUser.getPassword());
if (registeredUser != null) {
return ResponseEntity.ok("Registration successful");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Registration failed");
}
}

@PostMapping("/login")
public ResponseEntity<?> loginUser(@RequestBody User loginUser, HttpSession session) {
User user = userService.loginUser(loginUser.getUsername(), loginUser.getPassword());
if (user != null) {
session.setAttribute("userId", user.getUserId());
Map<String, String> response = new HashMap<>();
response.put("message", "Login successful");
return ResponseEntity.ok(response);
} else {
Map<String, String> response = new HashMap<>();
response.put("message", "Invalid credentials");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}
}

@PostMapping("/logout")
public ResponseEntity<?> logoutUser(HttpSession session) {
session.invalidate();
Map<String, String> response = new HashMap<>();
response.put("message", "Logged out successfully");
return ResponseEntity.ok(response);
}

@GetMapping("/test")
public ResponseEntity<String> testEndpoint() {
return ResponseEntity.ok("Test endpoint is working!");
}
}

</code></pre>
<pre><code>public class UserService {
private UserData userData = new UserData();

public User registerUser(String phoneNumber, String username, String password) {
return userData.registerUser(phoneNumber, username, password);
}

public User getUserById(String userId) {
return userData.getUserById(userId);
}

public User loginUser(String username, String password) {
return userData.loginUser(username, password);
}
}

</code></pre>
<pre><code>package Backend;

import java.util.ArrayList;
import java.util.List;

public class User {
private String userId;
private String phoneNumber;
private String username;
private String password;
private List<User> friends;

public User(String userId, String phoneNumber, String username, String password, List<User> friends) {
this.userId = userId;
this.phoneNumber = phoneNumber;
this.username = username;
this.password = password;
this.friends = friends;
}

// Getters and setters
}

</code></pre>
<pre><code>document.getElementById('registerForm').addEventListener('submit', function(event) {
event.preventDefault();
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
let phoneNumber = document.getElementById('phonenumber').value;

var userData = {
username: username,
password: password,
phoneNumber: phoneNumber
};

fetch('http://localhost:8080/api/users/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
})
.then(response => {
if (response.ok) {
alert('Registration successful!');
document.getElementById('registerForm').reset();
window.location.href = 'login.html';
} else {
throw new Error('Registration failed.');
}
})
.catch(error => {
console.error('Registration error:', error);
alert('Registration failed. Please try again later.');
});
});

</code></pre>
<p>Issue:
When I try to submit the registration form, I receive a 404 Not Found error. I have verified that my API is correctly deployed on Azure and should be accessible</p>
<p>I have:
Ensured that the Azure app service is running.
Verified that the endpoint /api/users/register is correctly defined in UserController.java.
Checked the CORS configuration in WebConfig.java to allow requests from all origins.
Confirmed that the JavaScript file (Register.js) is correctly linked and making a POST request to the correct Azure URL.</p>
Continue reading...
 

Latest posts

Top