如何在 jaxrs 中发送 application/json jQuery ajax 请求而不会出现“Access-Control-Allow-Origin”丢失错误
How to send application/json jQuery ajax request in jaxrs without having ‘Access-Control-Allow-Origin’ missing error
我的问题是当我从浏览器向 jaxrs api 服务器发送请求时,预检请求失败
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:9091/api/employee/add. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我不明白为什么我无法使预检请求成功。我的邮递员请求成功了。但是当从浏览器发送请求时它正在下降。
Ajax 请求:
$.ajax({
type: "POST",
url: "https://localhost:9091/api/employee/add",
cache: false,
data:JSON.stringify(employeeJSONObj),
dataType: "json",
contentType: 'application/json',
success: function(response){
});
Json 负载:
{
"employeeName":"Name3",
"nRIC":"NRIC3",
"dateOfBirth":"2017-01-02",
"address":"Address",
"salaryMode":"Monthly",
"bankAccount":"Bank Account",
"appointmentAs":"Security Supervisor (SS)",
"nationality":"Malaysian",
"maritalStatus":"Married",
"sex":"Female",
"nextOfKin":"Next Of kin",
"mobilePhone":"Mobile Phone",
"profilePicture":null,
"document":null
}
Jersy jaxrs API 服务器集成:
@POST
@Consumes({ MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON})
@Path("add")
public Response addEmployee(Employee employee) {
EmployeeImpl employeeImpl =
(EmployeeImpl) context.getBean("employeeImpl");
if (employeeImpl.validateEmployeeDetails(employee)) {
employeeImpl.addEmployee(employee);
employee.setSuccessMessage("Employee added successfully");
}else{
employee.setErrorMessage("employee detail insertion failed due to invalid" +
" inputs, please recheck inputs and retry");
return Response.ok().status(Response.Status.BAD_REQUEST)
.entity(employee)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
.header("Access-Control-Allow-Headers","Content-Type")
.build();
}
return Response.ok()
.entity(employee)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
.header("Access-Control-Allow-Headers","Content-Type")
.build();
}
Maven 依赖项:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.8</version>
</dependency>
请求headers:
Host: localhost:9091
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
如果是您的测试应用程序,您可以使用 Allow-Control-Allow-Origin chrome 扩展来启用允许交叉请求。
问题是关于同时使用8080和9091端口。
Host: localhost:9091
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080
并勾选 this
更新:
出现这个问题的原因是我没有在grizzle服务器中注册CORSFilter,在grizzle中注册CORSFilter后可以通过以下方式解决问题
需要按以下方式创建一个 CORSFilter class
public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization," +
"access-control-allow-origin," +
"Access-Control-Allow-Credentials");
response.getHttpHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
response.getHttpHeaders().add("Access-Control-Expose-Headers","authorization,errorMessage,successMessage");
return response;
}
}
注册 CORSFilter
ResourceConfig rc=new PackagesResourceConfig("hms.test.automation.system.tc.manager.resources"); // register resources
// Packages and exception mappers
rc.getContainerResponseFilters().add(CORSFilter.class);
我的问题是当我从浏览器向 jaxrs api 服务器发送请求时,预检请求失败
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:9091/api/employee/add. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我不明白为什么我无法使预检请求成功。我的邮递员请求成功了。但是当从浏览器发送请求时它正在下降。
Ajax 请求:
$.ajax({
type: "POST",
url: "https://localhost:9091/api/employee/add",
cache: false,
data:JSON.stringify(employeeJSONObj),
dataType: "json",
contentType: 'application/json',
success: function(response){
});
Json 负载:
{
"employeeName":"Name3",
"nRIC":"NRIC3",
"dateOfBirth":"2017-01-02",
"address":"Address",
"salaryMode":"Monthly",
"bankAccount":"Bank Account",
"appointmentAs":"Security Supervisor (SS)",
"nationality":"Malaysian",
"maritalStatus":"Married",
"sex":"Female",
"nextOfKin":"Next Of kin",
"mobilePhone":"Mobile Phone",
"profilePicture":null,
"document":null
}
Jersy jaxrs API 服务器集成:
@POST
@Consumes({ MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON})
@Path("add")
public Response addEmployee(Employee employee) {
EmployeeImpl employeeImpl =
(EmployeeImpl) context.getBean("employeeImpl");
if (employeeImpl.validateEmployeeDetails(employee)) {
employeeImpl.addEmployee(employee);
employee.setSuccessMessage("Employee added successfully");
}else{
employee.setErrorMessage("employee detail insertion failed due to invalid" +
" inputs, please recheck inputs and retry");
return Response.ok().status(Response.Status.BAD_REQUEST)
.entity(employee)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
.header("Access-Control-Allow-Headers","Content-Type")
.build();
}
return Response.ok()
.entity(employee)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, OPTIONS")
.header("Access-Control-Allow-Headers","Content-Type")
.build();
}
Maven 依赖项:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.8</version>
</dependency>
请求headers:
Host: localhost:9091
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
如果是您的测试应用程序,您可以使用 Allow-Control-Allow-Origin chrome 扩展来启用允许交叉请求。
问题是关于同时使用8080和9091端口。
Host: localhost:9091
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080
并勾选 this
更新:
出现这个问题的原因是我没有在grizzle服务器中注册CORSFilter,在grizzle中注册CORSFilter后可以通过以下方式解决问题
需要按以下方式创建一个 CORSFilter class
public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization," +
"access-control-allow-origin," +
"Access-Control-Allow-Credentials");
response.getHttpHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
response.getHttpHeaders().add("Access-Control-Expose-Headers","authorization,errorMessage,successMessage");
return response;
}
}
注册 CORSFilter
ResourceConfig rc=new PackagesResourceConfig("hms.test.automation.system.tc.manager.resources"); // register resources
// Packages and exception mappers
rc.getContainerResponseFilters().add(CORSFilter.class);