0

I'm trying to connect the frontend of an app made in Angular to a backend in Java. I'm trying to pass the data through an API and every time I try to do a post I get the following error:

missing header CORS "access-control-origin" status code: 403

Here's the code of the page I'm trying to do the post from:

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

name = "";
surname = "";
birthday: number = 0;
email = "";
nickname = "";
password = "";
pasDue!: string;
NameAlready!: string;
passAlready!: string;
constructor() { }

public onSubmit(form: NgForm){
    this.name = form.value.FullName;
    this.surname = form.value.Surname;
    this.birthday = form.value.birthday;
    this.email = form.value.eMail;
    this.nickname = form.value.Nickname;
    this.password = form.value.Password;
    this.pasDue = form.value.passwordDue;
    let nickname = this.nickname;
    let birthday = this.birthday;
    let email = this.email;
    let name = this.name;
    let surname = this.surname;
    let password = this.password;
    const url = `http://localhost:8080/api/v1/user?user_name=${this.nickname}&password=${this.password}&name=${this.name}&surname=${this.surname}&birth=${this.birthday}&e_mail=${this.email}`;
     //console.log("url"+url);
     try{
     fetch(url, {
       method: "POST",
       mode: "cors",,
       headers :{
         "Content-Type":"application/json",
         "Access-Control-Allow-Origin": "*",

       },
       body: JSON.stringify({ nickname, birthday, email, name, surname, password }),
       }).then((resp)=>{
       resp.json();
       }).then((data)=>{
       console.log(data);
       })}catch(err){
       console.log(err);
    
       }
  }
  public onSubmitNew(form: NgForm){
     this.passAlready = form.value.passswordAlready;
     this.NameAlready = form.value.eMail;
  }
  ngOnInit(): void {
  }

}

I built the database and also the backend. What am I doing wrong? I heard that it can be a cross-domain issue. If so, how to solve it?

EDIT: After the suggestion of carloliwanag I share with you the code of the controller class in spring boot which handles the calls to the database:

package com.example.demo.User;

import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "api/v1/user")
public class UserController {

    private final UserService userService;

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


    @GetMapping
    public List<UserOfPopster> getStudents(){
        return userService.getStudents();
    }

    @PostMapping
    public void registerNewUser(@RequestBody UserOfPopster user){
        userService.addNewUser(user);
    }

    @DeleteMapping(path = "{user_id}")
    public void deleteUser(@PathVariable("user_id") Long id){
        userService.deleteUser(id);
    }

    @PutMapping(path = "{user_id}")
    public void putUser(@PathVariable("user_id") Long userId, @RequestParam(required = false) String name, @RequestParam(required = false) String eMail){
        userService.updateUser(userId, name, eMail);
    }

 }

So should I add the enableCors function here? Can you please give me some examples of how can I structure it? (Please, don't write the function for me, just give me an example since I never wrote any of these functions before).

2
  • Have you tried adding the "Access-Control-Allow-Origin": "*" to your backend too ? Can you check stackoverflow.com/questions/44905898/… and see if you are okey to move forward please ? Commented Jan 24, 2024 at 5:02
  • Should i follow what the person who made the question was doing? I can't find the 'ContainerResponseFilter' class however... Commented Jan 24, 2024 at 11:26

3 Answers 3

1

It will be better if you can also share the backend code or describe which application server you have used. CORS is configured in the backend. The backend should be configured to set the allowed methods and allowed origins.

I suggest this post. I think the author really explained CORS very well.

Basing on the code and assuming it is a SpringBoot application, you can add allow-origin of the ip and port of the front end. this would be an example:

@CrossOrigin(origins = "http://localhost:9000")
@PostMapping
public void registerNewUser(@RequestBody UserOfPopster user){
   userService.addNewUser(user);
}

You also have other options to enable CORS globally. You can look into this post for better understanding. Hope this helps.

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

4 Comments

Edited the question with the code you requested, thank you for your answer however. Let me know if it's right, i'm sorry, i'm still learning we development so i hope i'm not annoying.
Thank you for the update. That definitely helped. I added a quick answer for it. Good luck with the learning! Everyone is learning. :)
Doesn't work still :(
It worked in the end, but now i'm doing the same with another type of upload and even if i added in the controller the annotation you showed me here i still get CORS error.
-1

You need to allow it from the backend side. Or if you are working locally and want a quick fix, use this command in your Run (Windows key + R) and type this :

chrome.exe --disable-site-isolation-trials --disable-web-security
--user-data-dir="D:\temp"

1 Comment

Thank you, i'm using firefox tho... Also, how do i allow it on the backend?
-1

you can use this command line to allow it from the backend side but please close all your chrome browser before running:

start chrome.exe  --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp --disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure

Comments

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.