Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spark CORS Access-control-allow-origin error

I'm using Spark with Java and Angular 1 on client side. I keep getting this '-1' error when I send request to the server. The error is "No 'Access-control-allow-origin' header is present on the requested resource. Origin 'http://localhost:4567' is therefore not allowed access."

I understand it's a CORS issue so I add header 'Access-Control-Allow-Origin' : '*' and added it as well to the response on server side. Unfortunately it doesn't seem to solve my problem.

Need your help guys, Thanks!

like image 748
Tom Dinur Avatar asked Aug 12 '26 06:08

Tom Dinur


2 Answers

Spark.after() is your friend

package com.company.package;

import static spark.Spark.*;

import com.google.gson.Gson;
import spark.Filter;
import spark.Request;
import spark.Response;

public class MyClass {

    public static void main(String[] args) {
        final Service service = new ServiceImpl();

        after((Filter) (request, response) -> {
            response.header("Access-Control-Allow-Origin", "*");
            response.header("Access-Control-Allow-Methods", "GET");
        });

        get( "/something", (req, res)->{
            res.type("application/json");
            return new Gson().toJsonTree(service.getNodes());
        });
    }
}
like image 115
MonoThreaded Avatar answered Aug 16 '26 05:08

MonoThreaded


I have used the following successfully (which I found here: https://gist.github.com/zikani03/7c82b34fbbc9a6187e9a):

//add correct package 

import com.mpaw.app.controllers.Apply;
import java.util.HashMap;
import spark.Filter;
import spark.Request;
import spark.Response;
import spark.Spark;

/**
 * Really simple helper for enabling CORS in a spark application;
 */
public class CorsFilter /*implements Apply*/{

    private final HashMap<String, String> corsHeaders = new HashMap<>();

    public CorsFilter() {
        corsHeaders.put("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        corsHeaders.put("Access-Control-Allow-Origin", "*");
        corsHeaders.put("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,");
        corsHeaders.put("Access-Control-Allow-Credentials", "true");
    }

    @Override
    public void apply() {
        Filter filter = new Filter() {
            @Override
            public void handle(Request request, Response response) throws Exception {
                corsHeaders.forEach((key, value) -> {
                    response.header(key, value);
                });
            }
        };
        Spark.after(filter);
    }
}

Usage:

public static void main(String[] args) {
    CorsFilter.apply(); // Call this before mapping thy routes
    Spark.get("/hello", (request, response) -> {
        return "Hello";
    });
}
like image 31
Quaternion Avatar answered Aug 16 '26 05:08

Quaternion