Spring Boot + Angular : Link has been blocked by CORS - javascript

I have a problem that I don't seem to figure out. I want to send a http request from my
Angular client
export class UsersService {
private baseUrl = 'http://localhost:8095/rest/users';
createUser(user: Object): Observable<Object> {
return this.http.post(`${this.baseUrl}` , user);
}
getUsers(): Observable<any> {
return this.http.get(`${this.baseUrl}/all`);
}
}
create user component.ts :
save() {
this.userService.createUser(this.user)
.subscribe(data => console.log(data), error => console.log(error));
this.user = new User();}
this is the SpringBoot backend
#RestController
#RequestMapping("/rest/users")
public class UsersResource {
private UserRepository userRepository;
public UsersResource(UserRepository userRepository) {
this.userRepository = userRepository;
}
#GetMapping("/all")
public List<Users> getAll() {
return userRepository.findAll();
}
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void create(#RequestBody Users users) {
userRepository.save(users);
}
}
when i call http://localhost:4200/users i got a clean result with all users without any problem
but when i want to add a user from here http://localhost:4200/adduser it show for me some issue
by the way iam using CORS chrome extension
i hope that someone help me for this isse.
thanks

Related

How to configure CORS in spring boot with spring security? [duplicate]

This question already has an answer here:
CORS Error: “requests are only supported for protocol schemes: http…” etc
(1 answer)
Closed 1 year ago.
I have a problem with the CORS. I have the following configuration of security:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CustomUserDetailsService userDetailsService;
#Autowired
private CustomJwtAuthenticationFilter customJwtAuthenticationFilter;
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(HttpSecurity http) throws Exception {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
corsConfiguration.setAllowedOrigins(List.of("*"));
corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT","OPTIONS","PATCH", "DELETE"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setExposedHeaders(List.of("Authorization"));
http.csrf().disable()
.authorizeRequests()
.antMatchers("/helloadmin").hasRole("ADMIN")
.antMatchers("/hellouser").hasAnyRole("USER","ADMIN")
.antMatchers("/techshop/web/v1/product/save").hasRole("ADMIN")
.antMatchers("techshop/web/v1/product").hasAnyRole("USER", "ADMIN")
.antMatchers("techshop/web/v1/product/{id}").hasRole("ADMIN")
.antMatchers("/authenticate").permitAll().anyRequest().authenticated()
.and().exceptionHandling()
//if any exception occurs call this
.authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//Add a filter to validate the tokens with every request
http.addFilterBefore((Filter) customJwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}
}
And I have the following controllers:
#RestController
#RequestMapping(value = "")
public class AuthenticationController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private CustomUserDetailsService customUserDetailsService;
#Autowired
private JwtUtil jwtUtil;
#PostMapping(path = "/authenticate", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> createAuthenticationToken(#RequestBody AuthenticationRequest request) throws Exception {
try{
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
request.getUsername(), request.getPassword()));
} catch (DisabledException e) {
throw new Exception("USER_DISABLE", e);
} catch (BadCredentialsException e){
throw new Exception("INVALID_CREDENTIALS", e);
}
final UserDetails userDetails = customUserDetailsService.loadUserByUsername(request.getUsername());
final String token = jwtUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(token));
}
}
And:
#RestController
#RequestMapping("techshop/web/v1")
public class ProductController {
#Autowired
private ProductServiceI productService;
#PostMapping(value = "/product/save", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> save(#RequestBody ProductDto request){
productService.save(request);
return ResponseEntity.ok(Boolean.TRUE);
}
#GetMapping(value = "/product", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> findAll(){
return ResponseEntity.ok(productService.findAll());
}
#PutMapping(value = "/product/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> updateProduct(#PathVariable("id") int id, #RequestBody ProductDto request){
productService.update(request, id);
return ResponseEntity.ok(Boolean.TRUE);
}
#DeleteMapping(value = "/product/{id}")
public ResponseEntity<Object> deleteById(#PathVariable("id") int id){
productService.deletedById(id);
return ResponseEntity.ok(Boolean.TRUE);
}
}
When I make the following request, the browser show the CORS problem:
let datos = {
username:"admin",
password:"admin"
}
const getToken = () => {
axios({
method: 'post',
url: 'localhost:8080/test',
data: datos
});
}
getToken()
enter image description here
I've tried everything, with the #CrosOrigin ("*") annotation, with lambdas, with a Bean WebConfig that extends from corsConfigurer, but nothing works.
I appreciate if you can help me.
Please try the following:
const getToken = () => {
axios({
method: 'post',
url: 'http://localhost:8080/test',
data: datos
});
}

How to get and send messages asynchronously from one websocket client to antoher

I need to establish connection between client websocket threw my backend on spring java to another websocket where my backend is a client, I established connection as client but can't figure out how to send it back as soon as my client send me message,
My Client Endpoint works as I need
#Service
#ClientEndpoint
public class ClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WbsClientEndpoint(#Value("${url}") String url) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, new URI(url));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening web socket");
this.userSession = userSession;
}
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing web socket");
this.userSession = null;
}
#OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
public interface MessageHandler {
void handleMessage(String message);
}
}
and example of method when I send my message as client, it does what I need but now I only printing the message cause cannot connect it to my message handler:
#Override
public void addDevice(DeviceTransfer deviceTransfer) {
clientEndPoint.addMessageHandler(message -> {
System.out.println("Response: " + message);
});
clientEndPoint.sendMessage(JSON.toJSONString(deviceTransfer));
}
Also I wrote a websockethandler for messages that comes to my backend:
#Component
public class WebSocketHandler extends AbstractWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
System.out.println("New Text Message Received" + message + " ___ " + session);
String clientMessage = message.getPayload();
if (clientMessage.startsWith("/addDevice")) {
//Here I don't know how to send this clientMessage and wait for result from my addDevice method to return it back
}
}
}
And I need to connect both of the realizations to establish connection in real time.
When client sends message to me I must send this message to another server as client.
My client code on JavaScript as example, when I press button it establish connection to my web socket and send my message:
const connectBtn = document.getElementById('connect');
if (connectBtn) {
connectBtn.addEventListener('click', function () {
window.socket1 = new WebSocket("ws://localhost:8081/ws");
socket1.onopen = function(e) {
console.log("[open]");
socket1.send(JSON.stringify({"command": "subscribe","identifier":"{\"channel\":\"/topic/addDevice\"}"}))
};
socket1.onmessage = function(event) {
console.log(`[message]: ${event.data}`);
};
socket1.onclose = function(event) {
if (event.wasClean) {
console.log(`[close],code=${event.code}reason=${event.reason}`);
} else {
console.log('[close]');
}
};
socket1.onerror = function(error) {
console.log(`[error] ${error.message}`);
};
});
}
It seems to me like you need to keep track of your ClientEndpoint instances:
public class ClientEndpoint {
private HashSet<ClientEndpoint> endpoints = new HashSet<>();
// or perhaps a HashMap using `userSession.id` or similar
private HashMap<string, ClientEndpoint> userToEndpoint = new HahsMap<>();
#OnOpen
public void onOpen(Session userSession) {
System.out.println("opening web socket");
this.userSession = userSession;
this.endpoints.add(this);
this.userToEndpoint.put(userSession.id, this);
}
#OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing web socket");
this.endpoints.remove(this);
this.userToEndpoint.delete(userSession.id);
this.userSession = null;
}
}
You can use endpoints/userToEndpoint to find all connected clients, perhaps filter by which rooms they're in (I assume that's what you're trying to accomplish with that subscribe command), and do whatever you want with that information. E.g. a broadcast to everyone except the sender:
for (ClientEnpoint endpoint : this.endpoints) {
if (endpoint == sender) continue; // Don't send to sender
endpoint.sendMessage("message");
}

Confused over how i should use an observable

i am trying to make a chat an angular node.js real-time chat application
i am using socket.io with angular and a nodejs backend
Server Side
io.on('connection', (socket) => {
socket.on('new-message', (message) => {
io.emit(message);
});
});
Client Side
service
private url = 'http://localhost:3000';
private socket;
constructor( private httpClient: HttpClient ) {
this.socket = io(this.url);
}
public sendMessage(message:Message){
this.socket.emit('new-message',message);
}
public getMessages = () => {
return new Observable(observer => {
this.socket.on('new-message', (message) => {
observer.next(message);
});
});
}
component
messages:any[]=[];
constructor(private chatService:ChatService){}
ngOnInit(): void {
this.chatService.getMessages()
.subscribe((message:any)=>{
this.messages.push(message);
})
onSubmit(){
//extracting message from the input form (not relevant i think i can add it if suggested)
this.chatService.sendMessage(tosend);
}
component.html
<div *ngFor="let m of messages">
{{m.text}}
</div>
<! -- a form to send messages -->
turns out issue was server side had to change
io.emit(message);
to io.emit('new-message',message)

Spring Security OAuth2 JWT CORS not allowed

I have a trouble with CORS configuration. I've followed few tutorials, videos on YT and I was looking for help here, on StackOverflow - but nothing helps me.
I have two backend projects (first one - Spring Boot 1.5.9 with OAuth2 and JWT, second one - Spring Boot 2.0.0 M7 with Spring Security 5 basic authentication) and my friend uses React for frontend. In both I have the same problem - when we want to login, server responses with 401 HTTP status and following message:
Failed to load http://localhost:8080/oauth/token: Response for preflight has invalid HTTP status code 401
Case 1 (Spring Boot 1.5.9 OAuth2 JWT)
In this project I have
SecurityConfig class that extends WebSecurityConfigurerAdapter
My implementation of AuthorizationServerConfigurerAdapter
And implementation of ResourceServerConfig
My ResourceServerConfig class looks like this:
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final String RESOURCES_IDS = "ResourceId";
private static final String SECURITY_REALM = "Spring Boot Realm";
private final TokenStore tokenStore;
#Autowired
public ResourceServerConfig(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCES_IDS)
.tokenStore(tokenStore);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(REGISTER_USER + "/**").permitAll()
.antMatchers(HttpMethod.GET, GEOTAGS_PATH + "/**").permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic()
.realmName(SECURITY_REALM)
.and()
.csrf().disable().cors();
}
}
AuthorizationServerConfig:
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final TokenStore tokenStore;
private final JwtAccessTokenConverter accessTokenConverter;
private final AuthenticationManager authenticationManager;
private final DataSource dataSource;
#Autowired
public AuthorizationServerConfig(TokenStore tokenStore,
JwtAccessTokenConverter accessTokenConverter,
AuthenticationManager authenticationManager,
#Qualifier("customDatasource") DataSource dataSource) {
this.tokenStore = tokenStore;
this.accessTokenConverter = accessTokenConverter;
this.authenticationManager = authenticationManager;
this.dataSource = dataSource;
}
#Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
configurer
.jdbc(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
final TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
enhancerChain.setTokenEnhancers(Collections.singletonList(accessTokenConverter));
endpoints.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter)
.tokenEnhancer(enhancerChain)
.authenticationManager(authenticationManager);
}
}
And finally SecurityConfig:
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String SIGNING_KEY = "Gz73RSOADKDFXzONqg3q";
private UserDetailsService customUserDetailsService;
private DataSource dataSource;
#Autowired
public void setCustomUserDetailsService(UserDetailsService customUserDetailsService) {
this.customUserDetailsService = customUserDetailsService;
}
#Autowired
public void setDataSource(#Qualifier("customDatasource") DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(SIGNING_KEY);
return converter;
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedHeaders(Collections.singletonList("*"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
As you can see I use CorsConfigurationSource Bean but when we run javascript code which is in different Origin:
fetch('http://localhost:8080/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${window.btoa('eTaxiClientId:secret')}`
},
body: `username=${encodeURIComponent('Admin')}&password=${encodeURIComponent('pass')}&grant_type=password`
});
Server response with message that I described on the beginning.
I have also tried use my implementation of WebMvcConfigurerAdapter with overridden addCorsMappings method, I tried to permitAll HttpMethod.OPTIONS but browser always sends OPTIONS request witch is matched with 401 code.
Case 2 (Spring Boot 2)
In this project I tried to use basic Spring Security authorization system - without OAuth2 and JWT. And my configuration is:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final MyUserDetailsService userDetailsService;
private final DataSource dataSource;
public SecurityConfig(MyUserDetailsService userDetailsService,
#Qualifier("customDatasource") DataSource dataSource) {
this.userDetailsService = userDetailsService;
this.dataSource = dataSource;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.servletApi().and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/1").hasAuthority("USER")
.antMatchers("/api/2").hasAuthority("ADMIN")
.antMatchers("/api/3").hasAuthority("GUEST")
.and()
.anonymous().principal("guest").authorities("GUEST")
.and()
.formLogin().permitAll()
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.logout()
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository())
.and()
.headers()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic()
.and()
.cors()
.and()
.csrf().disable();
// .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
#Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
#Bean
public PersistentTokenRepository tokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl = new JdbcTokenRepositoryImpl();
jdbcTokenRepositoryImpl.setDataSource(dataSource);
return jdbcTokenRepositoryImpl;
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
And in this case when we run following code in JavaScript application:
const body = `username=${encodeURIComponent('admin')}&password=${encodeURIComponent('pass')}`;
const hashedCredentials = btoa('admin:pass');
return axios.post(`${process.env.REACT_APP_API_URL}/login`, body, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// test oauth credentials
Authorization: `Basic ${hashedCredentials}`
}
})
.then(() => {
localStorage.setItem('user', hashedCredentials);
})
.then(() => {
const userCredentials = localStorage.getItem('user');
return axios.get(`${process.env.REACT_APP_API_URL}/api/2`, null, {
headers: {
Authorization: `Basic ${userCredentials}`
}
});
}).then(res => console.log(res)).catch(err => console.log(err));
OPTIONS request passes and we have status 200 response but as you can see we tried to redirect user to end point that is protected. But instead of displaying message on the screen, Spring Security redirects as to login page..
Summary
Have someone had such problem? Does someone see what we are doing wrong ? Why do we have problem in both projects? Is better (and safer) approach for user authentication?
I hope I haven't forgotten to describe something and I am looking forward for response. Cheers !

Angular Http.get request from servlet of project on local server (json data returns correctly, but not displaying, does work with a mock api)

Error in console:
Error with getting users from service. Response with status: 404 Not Found for URL: http://localhost:8080/ChatApp/GetAllUsersServlet
Same problem occurs when I deployed the external project somewhere, so with url:
http://java.cyclone2.khleuven.be:38034/ChatApp/GetAllUsersServlet
You can see for yourself is a working url with json in it, but stil 404 error.
Angular code expecting json from servlet running on local server:
export class UserService {
// private usersUrl = 'api/users'; // mock api
private usersUrl = 'http://localhost:8080/ChatApp/GetAllUsersServlet'; // external users from local server
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise() // Http.get returns RxJS Observeable, converted to Promise here
.then(response => response.json().data as User[]) // .data for mock inMemoryDataService
.catch(this.handleError);
}
What Servlet returns:
[{"fname":"TestFname","password":"test","gender":"Female","name":"TestName","id":1,"email":"test#test.com","age":21,"username":"Test","status":"offline"},{"fname":"Test4Fname","password":"test","gender":"Female","name":"Test4Name","id":4,"email":"test4#test.com","age":21,"username":"Test4","status":"offline"},{"fname":"Test3Fname","password":"test","gender":"Female","name":"Test3Name","id":3,"email":"test3#test.com","age":28,"username":"Test3","status":"offline"},{"fname":"Test2Fname","password":"test","gender":"Male","name":"Test2Name","id":2,"email":"test2#test.com","age":22,"username":"Test2","status":"offline"}]
This exact thing in a mock api, does give correct result:
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let users = [{"fname":"TestFname","password":"test","gender":"Female",
"name":"TestName","id":1,"email":"test#test.com","age":21,"username":"Test","status":"offline"},
{"fname":"Test4Fname","password":"test","gender":"Female",
"name":"Test4Name","id":4,"email":"test4#test.com","age":21,"username":"Test4","status":"offline"},{"fname":"Test3Fname","password":"test","gender":"Female","name":"Test3Name","id":3,"email":"test3#test.com","age":28,"username":"Test3","status":"offline"},
{"fname":"Test2Fname","password":"test","gender":"Male",
"name":"Test2Name","id":2,"email":"test2#test.com","age":22,"username":"Test2","status":"offline"}]
return {users};
}
}
Any help would be appreciated, since I really don't know why it won't work. Tried something similar but just less json data and that works.
Yes, the server for the servlet is running locally.
getUsers() gets used and displayed by this, but since it works with mock data, this should be okay?:
export class UsersComponent {
users: User[];
selectedUser: User;
constructor(
private userService: UserService,
private router: Router) { }
gotoInfo(): void {
this.router.navigate(['/info', this.selectedUser.username]);
}
onSelect(user: User): void {
this.selectedUser = user;
}
getUsers(): void {
this.userService.getUsers().then(users => this.users = users);
}
ngOnInit(): void {
this.getUsers();
}
}
Servlet (cors enabled):
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserDB db = new UserDB();
JSONArray array = new JSONArray();
for (User users: db.getAll()) {
try {
array.put(users.getJSONObject());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// setting the response type to json
response.setContentType("application/json");
// setting the CORS request
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().write(array.toString());
Previously using in-memory-web-api will mess with your http-requests unless you remove something like the following InMemoryWebApiModule.forRoot(InMemoryDataService) from your NgModule, then your requests should be going fine.
EDIT: Realized based on code comment that you knew the following:
After this is done, I can also point out that you have a problem in your get request, as it stands you will not get any data in your component. Your response just contains an array, not data, so it should be just:
.then(response => response.json() as User[])

Categories