Jeresy CORS filter working but React rest GET failing still with header ‘access-control-allow-origin’ is not allowed - reactjs

I create a rest react front end to talk to a Jersey servlet on tomcat on the back end for RH 8.6. When react tried to do on REST GET or POST commands I got the "‘access-control-allow-origin’ is not allowed according to header" error. So I then added the CORS filter which was suppose to fix the origin problem, but the react client is still failing. I have tried different filters but there is no change. I assume the problem is in the react GET fetch but it looks ok with me and gets a header back when mode: 'no-cors' is set. In the debugger the CORSFilter class gets the GET, but it does not reach the resource class endpoint so its getting rejected.
Using postman I have verified the CORSFilter is inserting the values in the response as you can see here.
POST http://localhost:8080/rtc-servlet/mcd/location
Headers from postman tool:
Status Code: 200
access-control-allow-credentials: true
access-control-allow-headers: X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type
access-control-allow-methods: API, GET, POST, PUT, DELETE, OPTIONS, HEAD
access-control-allow-origin: *
access-control-max-age: 151200
connection: keep-alive
content-length: 701
content-type: application/json
date: Sat, 10 Dec 2022 02:52:19 GMT
keep-alive: timeout=20
servlet code:
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
// *(allow from all servers) OR https://crunchify.com/
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
// As part of the response to a request, which HTTP headers can be used during the actual request.
responseContext.getHeaders().add("Access-Control-Allow-Headers",
"X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type");
Also tried these options:
"Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add("Access-Control-Allow-Methods",
"API, GET, POST, PUT, DELETE, OPTIONS, HEAD");
// How long the results of a request can be cached in a result cache.
responseContext.getHeaders().add("Access-Control-Max-Age", "151200");
}
}
#GET // read in updated/original files
#Produces(MediaType.APPLICATION_JSON) // what format we send back
public JsonObject getLocationValues() {
System.out.println("Called location getLocationValues ");
return locationRepository.readConfigFile(false);
}
React Rest GET fetch:
const urll1 = "http://localhost:8080/rtc-servlet/mcd/location";
useEffect(() => {
const fetchPost = async () => {
await fetch(urll1, {
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
})
.then((response) => {
if (response.ok) {
response.json().then(data => {
console.log("response fetchPost :" + JSON.stringify(data));
setPosts1(data);
});
} else {
console.log("response was not ok");
}
})
.catch((err) => {
console.log(err.message);
});
};
fetchPost();
}, []);
The console error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: CORS request did not succeed). Status code: (null).
NetworkError when attempting to fetch resource.
So does anyone see that I am doing wrong?

After read the CORS not working posts in stackoverflow again I came across a commit about getting the origin from the header and then setting Access-Control-Allow-Origin to it vs. "*" and react on port localhost:3000 started to get responses back from the localhost:8080 servlet (origin is being set to "localhost:3000"). This was the forum string if you want to read up on it:
How to enable Cross domain requests on JAX-RS web services?.
So the change in the filter class is as follows:
String origin = requestContext.getHeaderString("origin");
if ((origin != null) && (!origin.isEmpty())) {
headers.add("Access-Control-Allow-Origin", origin);
} else {
// *(allow from all servers) OR https://crunchify.com/
headers.add("Access-Control-Allow-Origin", "*");
}
headers.add("Access-Control-Allow-Credentials", "true");
and in the js script "Access-Control-Allow-Origin": "*" was deleted:
await fetch(urll1, {
headers: {
'Content-Type': 'application/json',
"Accept": "application/json"
},
})
I am not sure if I now need the else since "*" didn't work for me, but I left it in. If its not needed or I am just doing something that sort of works because I am using firefox please let me know.

Related

DELETE request's preflight fails on Firefox for Quarkus

I'm getting a very strange error which I'm having a very hard time understanding why it's occurring.
Setup
I have a Quarkus backend which serves the following endpoints:
#Path("/rest/manager")
#ApplicationScoped
public class ManagerController {
...
#GET
#Path("/")
public Response getManagerList() {
...
}
#POST
#Path("/")
public Response createManager(#Valid ManagerView managerView) {
...
}
#GET
#Path("/{userId}")
public Response getManager(#Parameter(required = true) #PathParam("userId") String userId) {
...
}
#DELETE
#Path("/{userId}")
public Response deleteManager(#Parameter(required = true) #PathParam("userId") String userId) {
...
}
#PUT
#Path("/{userId}")
public Response updateManager(#PathParam("userId") String userId, #Valid ManagerView managerView) {
...
}
}
Quarkus application.properties looks like this:
quarkus.http.cors=true
quarkus.http.cors.origins=http://localhost:3000
quarkus.http.cors.methods=GET,POST,PUT,DELETE,OPTIONS
My frontend runs on localhost:3000 and backend on localhost:8080.
Frontend is in React, and i'm using axios to make the call like this:
.post<ManagerView>(`/manager`, managerToManagerView(data.manager), {
headers: {
Authorization: `Bearer ${data.accessToken}`,
'Content-Type': 'application/json',
},
})
...
.delete<boolean>(`/manager/${userId}`, {
headers: {
Authorization: `Bearer ${data.accessToken}`,
},
})
The Error
In Firefox, I get the following error when i make a Delete request.
XHR OPTIONS http://localhost:8080/rest/manager/auth0|63de17288141500bc6ac65e0
CORS Missing Allow Origin
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rest/manager/auth0|63de17288141500bc6ac65e0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rest/manager/auth0|63de17288141500bc6ac65e0. (Reason: CORS request did not succeed). Status code: (null).
Here's a screenshot from the Browser's devtools:
As you can see, just before the DELETE request, there is a POST request and the preflight for that is successful.
This is the details of the preflight which fails (the one before DELETE):
Also for comparison, here is the preflight request which doesn't fail (The one before POST)
This error only happens on DELETE or PUT. Other methods (POST and GET) are working fine.
This error only happens on Firefox, not on Chrome or Edge
Another interesting detail might be that on Chrome it doesn't work if I don't supply the Authorization header
I have tried various CORS settings for Quarkus however nothing works.

Getting Axios from React to Work with Spring Boot + Spring Boot Security

I have created a react app with a spring boot backend but I'm having trouble pulling the data through with axios.
I have checked numerous SO posts as well as documentation with spring to no avail. I was initially blocked by CORS but I was able to resolve that with Spring Security. However, spring security requires authentication, I've been using the default user "user" with the randomly generated password (since I can't get a newly defined user/password defined with AuthenticationManagerBuilder to work just with queries against the server directly in a browser but that's an issue for another day). Below is my configuration file for the server.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
http.cors().and();
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
My server runs on localhost port 9898, the query I'm initially trying to pull data from on the front end is a get by id for contact info which goes against http://localhost:9898/api/Contact/1
when I successfully call the server from a browser directly the header details are as depicted:
call from browser to server general and response headers
call from browser to server request headers
notice that authorization header is actually there in the request.
For the RestController I've got cross origin set to the client running on port 3000. I do have a header being adding in the getContactMethod as suggested in a tutorial but I don't think this actually changed anything since I have this header being set in the configuration file anyway.
#CrossOrigin(origins = "http:localhost:3000")
#RestController
#RequestMapping("/api/Contact")
public class ContactController {
#Autowired
private ContactRepository ContactRepository;
#GetMapping("/")
public List<Contact> getContacts(){
return this.ContactRepository.findAll();
}
#GetMapping("/{id}")
public Contact GetContact(#PathVariable Long id, HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "**");
return ContactRepository.findById(id).orElse(null);
}
For the client I have a file creating an axios instance, I'm not sure if this part is right since I never reference the specific instance again but maybe axios can figure this out on it's own if there is only one instance.
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:9898",
});
// api.defaults.headers.common = {
// 'X-Requested-With': 'XMLHttpRequest'
// };
export default axios;
Now for the actual page on the front end I am attempted to load the requested data into the state variable from the useEffects event, which will need to be modified a little bit further but I can't go forward with that until the request works.
I've got numerous headers loaded in based on a combination of what I've come across online but the one I want to focus on is the authentication since that won't actually show up in the request when I look with dev tools on the network. I've got the password which is randomly set by spring security each time the back end is run hard coded and then this hard coded user:password value is encoded and added to the headers. Below is the relevant code:
const tok = 'user:9de3a921-a4af-4d51-b8d7-cf37b208916e';
const hash = btoa(tok);
const Basic = 'Basic ' + hash;
const headers = {
"Cache-Control": "no-cache",
"Accept-Language": "en",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
//"Authorization": "Basic dXNlcjowM2VhN2JhYS1mMTQ0LTQ5YWMtOGFhMy02NDE4YWJiNzdhMTk=",
'Authorization': `Basic ${hash}`,
};
useEffect(() =>{
console.log(Basic);
axios.get("http://localhost:9898/api/Contact/1", headers)
.then((res) => {
console.log("data " + res.data);
console.log("response header " + res.headers['Authorization']);
setInfo(res.data);
}).catch(err => console.log("error found " + err));
console.log(info);
}, []||[]);
When this is run I get a 401 unauthorized but for some reason the authorization header doesn't show up in the request headers.
General and response headers for request from client to server
Request headers for request from client to server
I feel like I'm fairly close with this but most of the tutorials on the spring site are simpler and the best practices for spring security have changed over the years so there is a lot of conflicting information and incomplete examples on the web. I figure I either have an issue in the security configuration or I guess I've set the headers up incorrectly but I don't have enough experience with spring and react I've just been troubleshooting in circles for a couple days.
Sources tried already (had to put some spaces in the links since I just made this account to post a question):
https://stackoverflow com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application/37610988#37610988
I should mention with this one below I added in .antMatchers(HttpMethod.Options, "/**").permitAll() and the headers were different but the request still didn't work and eventually the server would just crash shortly after starting with it
https://stackoverflow com/questions/41075850/how-to-configure-cors-and-basic-authorization-in-spring-boot/60933851#60933851
https://stackoverflow com/questions/58901586/how-to-fix-spring-security-authorization-header-not-being-passed
https://spring io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
https://spring io/guides/gs/rest-service-cors/
https://spring io/guides/gs/rest-service/
https://docs.spring io/spring-security/reference/reactive/integrations/cors.html
https://www.baeldung com/spring-security-cors-preflight
There is an issue with how the headers are are being passed to axios. The axios documentation defines axios.get like this axios.get(url[, config])
There are two parameters here. The first is the url, and it is required. The second is an optional config object.
The config object has a headers field.
You should pass in the headers like this:
const headers = {
'Cache-Control': 'no-cache',
'Accept-Language': 'en',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'DELETE, POST, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
//"Authorization": "Basic dXNlcjowM2VhN2JhYS1mMTQ0LTQ5YWMtOGFhMy02NDE4YWJiNzdhMTk=",
Authorization: `Basic ${hash}`
};
const config = {
headers
};
axios.get('http://localhost:9898/api/Contact/1', config);
I was looking back at the similar post I referenced earlier How to configure CORS in a Spring Boot + Spring Security application?
and I tried out the 4th most updated answer by user Soroosh Khodami Mar 11, 2021 and used their SecurityConfig.
#Override
protected void configure(HttpSecurity http) throws Exception {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000"));
corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT","OPTIONS","PATCH", "DELETE"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setExposedHeaders(List.of("Authorization"));
// You can customize the following part based on your project, it's only a sample
http.authorizeRequests().antMatchers("/**").permitAll().anyRequest()
.authenticated().and().csrf().disable().cors().configurationSource(request -> corsConfiguration);
}
My previous config was missing:
setAllowedHeaders(Listof("Authorization",..))
setAllowCredentials(true)
setExposedHeaders(Authorization)
this then lead me to a secondary issed which was caused by setting the header in my restcontroller get by id method.
response.setHeader("Access-Control-Allow-Origin", "**");
I got an error saying this was not allowed so then I changed it to "/**" and it still complained so I just commented it out and it worked. So if a tutorial suggests this (for me it was a youtube video about getting cors to work) I believe it is out of date/not best practice when you should set Access-Control-Allow-Origin in your Web Security Configuration.

Blocked by CORS policy "...does not have HTTP ok status" (Amplify and ReactJS, AWS Gateway and Lambda)

I'm almost embarassed to be asking this question due to CORS support out there on SO but I can't get by:
Access to XMLHttpRequest at 'https://a93xxxxx.execute-api.eu-west-1.amazonaws.com/dev[object%20Object]' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I've even published my React project with Amplify and attempted it from the real domain name to even eliminate anything to do with the development environment (Cloud 9 running npm version 6.14.8)
I've also made a test running Chrome with the --disable-web-security flag.
My Lambda function contains the following (out of the box stub)
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers" : "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
"Access-Control-Allow-Methods" : "OPTIONS,POST,GET,PUT"
}
,
body: JSON.stringify("Hello from Lambda!")
};
return response;
};
Note that I've uncommented the CORS request part and the response statusCode is set to 200.
The code in my application that execute when a submission form is sent from the client:
uploadcontactusdata = async data => {
try {
console.log("Contact Us pressed")
const settings = {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const fetchResponse = await API.post('econtactus', settings);
Notification({
title: 'Success',
message: 'Notification has been sent',
type: 'success'
});
}
catch (err) {
console.log("unable to send");
console.error(err)
}
}
I created the API Gateway + Lambda using Amplify (version 4.41.2). Not sure where else to look now. Any clues will be appreciated. Thanks
You can completely get past the need for api gateway by using appsync.
amplify add api
Choose graphql (I have not tried using rest but you shouldn't need it) choose the basic schema, edit it if you'd like, and publish. Once it's published you can create your own method. You can view this inside the AppSync UI under Schema.
type Mutation {
yourMethod(input: Input!): TableName <-- add your method to the list
}
Now inside Appsync choose Data Sources and add datasource. Give it a name, choose lambda as the type, then find your lambda in the list. Once it's added go back to your schema and find the method you created above. On the right side bar locate your method and click the attach link. Find the data source you just added. Fill out the region and lambda ARN. MAKE SURE you choose new role and not an existing one.
You might need to configure the request and response templates.
For request:
{
"version" : "2017-02-28",
"operation": "Invoke",
"payload": $util.toJson($context.args)
}
For response:
$util.toJson($context.result)
Now you can call your lambda directly from the UI and return your result without worrying about CORS or managing API Gateway.

Why in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error

I'm making axios call to my php API (which shows user data when a valid token is sent back to API server) and sending a valid jwt token in request header (along with Bearer as prefix) and in the Network's tab its showing that my token is being sent in the header but still it gives me 401 error and returns the Error msg of API that "jwt is empty"...
my API to fetch user data (when valid token is provided) is on http://localhost/Auth/api/validate.php
and client side is on http://localhost:3000
This API is in php and works perfectly fine on Postman. But gives me 401(unauthorized) when I call it in react. I searched this error and everyone says that u should have token in the Request header, I do have it but its not being read by the server and server considers it null so sends me unauthorized error. Please Please help me someone!!!!!
here is the axios API call:
e.preventDefault();
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',token, {
headers: {
'Authorization' : 'Bearer '+token,
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});
Response Headers
> Request URL: http://localhost/Auth/api/validate.php
> Request Method: POST
> Remote Address: [::1]:80
> Status Code: 401 Unauthorized
> Referrer Policy: no-referrer-when-downgrade
> Accept: application/json; charset=UTF-8, */*
> Access-Control-Allow-Credentials: true
> Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With
> Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
> Access-Control-Allow-Origin: *
> Access-Control-Exposed-Header: true
> Authorization Access-Control-Max-Age: 33600
> Connection: Keep-Alive
> Content-Length: 34
> Content-Type: application/json; charset=UTF-8, */*
> Date: Sat, 23 Mar 2019 12:33:00 GMT Keep-Alive: timeout=5, max=99
> Server: Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.3 X-Powered-By:
> PHP/7.2.3
Request Headers:
> Provisional headers are shown Accept: application/json, text/plain, */*
>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
> Content-Type: application/json
> Origin: http://localhost:3000
> Referer: http://localhost:3000/profile
> User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
> Request Payload: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNDQiLCJDb21wYW55TmFtZSI6IlRhZGEiLCJDb250YWN0UGVyc29uIjoiVGFkYSIsIkNvbnRhY3RObyI6Ijg3ODciLCJlbWFpbCI6InRhZGFAZ21haWwuY29tIn19.YmaD_VjMKYifWXd4DsRXRodVDpBy8zASLnIfgquCwLI
Here is my API validate.php
<?php
// required headers//
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8, */*");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 33600");
header("Content-Length: 144");
header("Accept: application/json; charset=UTF-8, */*");
header("Access-Control-Exposed-Header: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Accept, X-Auth-Token, Origin, Authorization, Client-Security-Token, Accept-Encoding, X-Requested-With");
// required to decode bbbb
include_once 'config/core.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/BeforeValidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/ExpiredException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/SignatureInvalidException.php';
include_once 'libs/php-jwt-master/php-jwt-master/src/JWT.php';
use \Firebase\JWT\JWT;
// get posted data
$data = json_decode(file_get_contents("php://input"));
// get jwt
$jwt=isset($data->jwt) ? $data->jwt : "";
// if jwt is not empty
if($jwt){
// if decode succeed, show user details
try {
// decode jwt
$decoded = JWT::decode($jwt, $key, array('HS256'));
// set response code
http_response_code(200);
// show user details
echo json_encode(array(
"message" => "Access granted.",
"data" => $decoded->data
));
}
// if decode fails, it means jwt is invalid
catch (Exception $e){
// set response code
http_response_code(401);
// tell the user access denied & show error message
echo json_encode(array(
"message" => "Access denied. Decode fails",
"error" => $e->getMessage()
));
}
}
// show error message if jwt is empty
//gggg
else{
// set response code
http_response_code(401);
// tell the user access denied
echo json_encode(array("message" => "Access denied. Empty"));
}
?>
EDIT
I also tried sending the token without 'Bearer' prefix but it didnt work. On Postman I send a post request (in the body) to my server API like this(which works fine):
{
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7IlZlbmRvcklEIjoiNTkiLCJDb21wYW55TmFtZSI6IkVub3VnaCIsIkNvbnRhY3RQZXJzb24iOiJlbm91Z2giLCJDb250YWN0Tm8iOiIzNDM0NCIsImVtYWlsIjoiZUBnbWFpbC5jb20ifX0.o4V6zu8AFBAMoJgRe_jvMoByDK3yDEiF_pxW4ttqpYQ"
}
The php code is expecting JWT token in the body. The token should be in a JSON as shown below.
const token = localStorage.getItem("jwttoken");
axios.post('http://localhost/Auth/api/validate.php',{"jwt":token}, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}} )
.then(response =>
{
console.log(response.data);
console.log(response);
return response;
})
.catch(error => {
if (error) {
console.log("Sorry.....Error"); }
});

Angularjs Bad Request with Spring+Jersey+Jackson

i am trying to insert a row in a database table using a POST request, but i get BAD REQUEST error.
This is my API
#POST
#Path("/insert")
#Consumes(MediaType.APPLICATION_JSON)
#Transactional
public Response setShop(Shop shop) throws Exception {
daoShop.insertShop(shop);
return Response.ok()
.entity(shop)
//.header("Access-Control-Allow-Origin","*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, origin, content-type, accept, authorization")
.allow("OPTIONS")
.build();
}
#OPTIONS
#Path("/insert")
public Response preflight(
#HeaderParam("Access-Control-Request-Method") String requestMethod,
#HeaderParam("Origin") String origin,
#HeaderParam("Access-Control-Request-Headers") String requestHeaders) {
return Response
.ok()
//.header("Access-Control-Allow-Origin", "*") // TODO replace with specific origin
.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, origin, Content-Type")
.build();
}
and this is my piece of angular code trying to contact the mapped API:
var datas = {"id":1,"name":"InsertNegozio1", "logofile":"logo", "coverfile":"cover", "address":"via di qui", "postalCode":"popopo", "city":"Dubai", "country":"Krypton", "description":"vomito", "openSince":2015-11-14, "closingStart":2015-11-14, "closingEnd":2015-11-14, "phoneNumber":"0598621", "email":"aaa#ggg.it"};
//datas: JSON.stringify(datas);
$http({
method : "POST",
url : "http://localhost:8080/shop/insert",
data : datas,
headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin' : '*'}
}).then(function mySucces(response) {
}, function myError(response) {
});
I tried uncommenting the stringify row but it still gives me error..
The JSON has all the fields of the Shop object that should be mapped, so i don't understand why i get BAD REQUEST..
EDIT: no errors on java side logging, the server responds with bad request, this is what i can see on js console on chrome (note: the class is mapped on /shop, the method on /insert)
POST http://localhost:8080/shop/insert 400 (Bad Request)

Resources