0

I'm trying to make a request from my reactjs client side (running on webpack server) to my testing backend in java.

both are localhosted but on different ports (3000 and 8888).

When i am using postman to request to my backend i get the expected response, so all seems to going right.

However, when i want to request from react, i have this error related to CORS :

XMLHttpRequest cannot load http://localhost:8888/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I think my backend server doesn't allow http request from my react server. So i need to find a way to let my backend know that it's okay to for handle request from react.

There is my test backend. Like i said before my backend is used as an API not as a servlet.

public class test {
        public Name getName() {
            Name name = new Name("John");
            return name;
        }
}

Any solution ?

1
  • 1
    You'll need to add "Access-Control-Allow-Origin" in response header Commented Jan 5, 2017 at 5:10

3 Answers 3

1

I dont know about Java specifically, but you need to modify the response headers on the Java end.

For development (only in development) you need to have the following header in place:

header("Access-Control-Allow-Origin", "*")

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

2 Comments

This is the right answer but I don’t see any reason to qualify it with “only in development”. If the server is not behind an intranet/firewall and anybody can make requests to the server using postman or curl or whatever then there’s almost always no good reason not to send the Access-Control-Allow-Origin: * header. The only case generally is if credentials need to be also be sent in requests. But all that said, if this server is inside some intranet or firewall then that’s a different story.
Very true, it sounds like the original poster was perhaps new to serving content from a server, so I was being better safe than sorry. I also lean towards only opening up what is absolutely needed, rather than opening everything and tighten up access. The original poster didn't reveal any details about his/her production environment, so I can't in good conscious give any advice that could accidentally applied to a production environment without knowing the full story.
1

You should add 'Access-Control-Allow-xxx' at the header of response on your server-side.

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8");

Comments

0

This is because you will need to add CORS headers to allow cross origin access. You can do that by adding headers to the response you are sending like the code below:

@GET
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getPodcastById(@PathParam("id") Long id, @QueryParam("detailed") boolean detailed)
        throws IOException, AppException {
    Podcast podcastById = podcastService.getPodcastById(id);
    return Response.ok()
            .entity(podcastById, detailed ? new Annotation[]{PodcastDetailedView.Factory.get()} : new Annotation[0])
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
            .allow("OPTIONS").build();
}

For further reference on CORS headers: http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/#2_Adding_HTTP_headers_to_resources_with_Jersey

In case of spring, you can do as follows:

package hello;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
        System.out.println("==== in greeting ====");
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

}

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.