Can’t call a GET method in a Spring Boot RestController from a simple Ajax function

  ajax, cors, php, spring-boot, ubuntu

I have a RestController in Spring Boot (version 2.1.6.RELEASE) in a Ububtu Server (in a Azure).

Ubuntu information’s:

Description: Ubuntu 18.04.5 LTS,
Release: 18.04,
Codename: bionic

My RestController has a GET method with this definition:

   @RequestMapping(value = "/universidades_por_prioridad", method = RequestMethod.GET)
   public Collection<UniversidadEntity> obtenerTodasPorPrioridad() {
      return universidadService.obtenerTodasPorPrioridad();
   }

That method returns a Collection of Universities (that list was get from the database)

Also I have this CORS configuration

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

   private static final Logger LOG = LoggerFactory.getLogger(CorsConfig.class);

   @Override
   public void addCorsMappings(CorsRegistry registry) {
      LOG.info("Adding CORS Mapping");
      registry.addMapping("/**").allowedOrigins("http://localhost").allowedMethods("PUT", "DELETE", "POST", "GET")
            .allowCredentials(false).maxAge(3600);

      // here I put the public server IP
      registry.addMapping("/**").allowedOrigins("http://52.XXX.XXX.XXX").allowedMethods("PUT", "DELETE", "POST", "GET")
            .allowCredentials(false).maxAge(3600);
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      LOG.info("Disabling CORS");
      http.cors().and().csrf().disable() //
            .authorizeRequests().antMatchers("/**") //
            .access("hasIpAddress("127.0.0.1") or hasIpAddress("::1") or hasIpAddress("::9002")") //
      ; //
   }

}

I have an Ajax inside a PHP that calls that Rest via GET.

My Ajax to call this GET is below:

jQuery.ajax({
    url: 'http://localhost:9002/universidades_por_prioridad',
    type: 'get',
    cache: false,
    async: true,
    dataType: 'json',
    success: function(universidades) {
        console.log(universidades);     
    }
});

My Spring Boot is configured to run in port 9002.

The application.properties has below:

server.port=9002
server.address=localhost

Both modules are inside the same server (all in the Ubuntu Server in Azure).

If I execute a CURL in the command line of the server, it returns the JSON with the universities list.

curl -i http://localhost:9002/universidades_por_prioridad

HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 02 Aug 2021 03:04:46 GMT
[{THE JSON}]

But from the Ajax I can’t reach the method.

  • The Chrome DevTools shows this:

GET http://localhost:9002/universidades_por_prioridad?_=123456789 net::ERR_CONNECTION_REFUSED

  • The Firefox DevTools shows this:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9002/universidades_por_prioridad?_=123456789. (Reason: CORS request did not succeed).

I found a lot of pages to do my configuration but in this server it was impossible.

In my computer with Windows 10 it works correctly but in the Ubuntu (in Linux in general) I couldn’t get it work.

Other info:

Java version: 1.8.0_292

PHP version: 7.2.24

Should also I have to modify something in the .htaccess from my PHP module?

Please, tell me someone what I need or what I am missing.
Thanks.

Source: Ask PHP

LEAVE A COMMENT