I have a problem doing CORS post request.
Here is the code for the post request:
/**
* function to update channel information
* @returns {undefined}
*/
this.postNameInfo = function() {
var channel = self.selected.split("-")[0];
var id = channel.replace("CH","");
$.ajax({
url: self.ioConfigurationUrl + "/" + id,
type: "POST",
data: {
"data": "name:" + $("#name")[0].value
},
success: function() {
console.log("Change name succeed!");
self.updateIoInfo();
self.updateStorageInfo();
$("#title").val($("#name")[0].value);
self.postTitleInfo();
},
error: function() {
console.log("Failed to change name of " + channel)
}
});
};
The server side code is here:
@POST
@Path("/{id : \\d+}")
@Produces(MediaType.APPLICATION_JSON)
public Response updateIOConfig(@PathParam("id") Integer id, @QueryParam("data") String data) {
if (!ChannelName.isValidChannel(id)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
init();
IOConfiguration ioConfig = ioConfigurationDAO.findIOConfiguration("CH" + id);
String key = data.split(":")[0];
String value = data.split(":")[1];
if (!ioConfigurationDAO.getManager().getTransaction().isActive()) {
ioConfigurationDAO.getManager().getTransaction().begin();
}
System.out.println(data);
if (key.equals("name")) {
ioConfigurationDAO.changeName(ioConfig.getIoConfigurationId(), value);
ioConfigurationDAO.getManager().getTransaction().commit();
if (ioConfig.getDataSeriesMeta() != null && ioConfig.getDataSeriesMeta().size() != 0) {
List<DataSeriesMeta> list = ioConfig.getDataSeriesMeta();
DataSeriesMetaDAO dataSeriesMetaDAO = new DataSeriesMetaDAO();
dataSeriesMetaDAO.setManager(ioConfigurationDAO.getManager());
if (!dataSeriesMetaDAO.getManager().getTransaction().isActive()) {
dataSeriesMetaDAO.getManager().getTransaction().begin();
}
for (DataSeriesMeta d : list) {
dataSeriesMetaDAO.changeName(d.getDataSeriesMetaId(), value);
}
dataSeriesMetaDAO.getManager().getTransaction().commit();
return Response.status(Response.Status.OK).entity(ioConfig).build();
}
}...
}
On my server side, I am always receiving null value and the browser will give me this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/aigateway/rest/ioconfiguration/1 . (Reason: CORS header 'Access-Control-Allow-Origin' missing).
It seems to me that my CORS filter is not working.
But if I am sending post request from RESTeasy to
http://localhost:8080/aigateway/rest/ioconfiguration/1?data=name:123
It will give me a 200 OK response with the correct information like
{"ioConfigurationId":"CH1","active":true,"name":"123","conversionType":"Linear","mInfo":5.93,"bInfo":0.32,"voltageDivide":"/4","sampleRange":"24 Bits","samplePeriod":10,"storeRaw":false,"storeConverted":false,"defaultGraph":"Line","title":"","unit":"","rangeLowerbound":0,"rangeUpperbound":100,"code":"function conversion_CH1 (input) {\\n\\treturn input;\\n}"}
And I can check the header, it is:
X-Powered-By Undertow/1
Access-Control-Allow-Headers origin, content-type, accept, authorization, Access-Control-Request-Method, Access-Control-Request-Headers
Server WildFly/10
Date Mon, 27 Mar 2017 14:41:24 GMT
Connection keep-alive
Access-Control-Allow-Origin *
Access-Control-Allow-Credentials true
Content-Type application/json
Content-Length 357
Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age 1209600
That's what I have added in my CORS filter, it's working in RESTeasy but not in my project, it's so strange, I don't know why.
For more information, here is how I set up my CORS filter:
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
cres.getHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization, Access-Control-Request-Method, Access-Control-Request-Headers");
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>servlet 3.0 Web Application</display-name>
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>
com.sensorhound.aigateway.ws.filters.CORSFilter
</param-value>
</context-param>
<servlet>
<servlet-name>ServletContainer</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.sensorhound.things.rest.ThingsApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletContainer</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
If you need more information, I am willing to share.
Thanks!
EDIT :
According to NrN, I have removed Access-Control-Allow-Credentials field in my CORS filter, but it still don't work.
Here is the request header in my browser's network console: Request Header: Accept*/*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Content-Length 18
Content-Typet ext/plain
Host localhost:8080
Origin null
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Here is the Response header: Response Header:
Connection keep-alive
Content-Length 9437
Content-Type text/html;charset=UTF-8
Date Tue, 28 Mar 2017 21:16:46 GMT
There are 2 problems here.
In the Jquery client request you do not have the withCredentials attribute set to true, but the server is trying to respond Access-Control-Allow-Credentials as true. Place this inside the ajax call. xhrFields: { withCredentials: true }
When you set Access-Control-Allow-Credentials to "true", you cannot have Access-Control-Allow-Origin as "*". You must specify a specific origin rather than the wildcard. More details here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.