【发布时间】:2021-05-16 12:41:53
【问题描述】:
我正在实现一个项目,前端使用 vue.js,后端使用 RESTful Web 服务(使用 Grizzly 和 Jersey 实现)。我实现了两个可访问的 API,一个带有 GET 请求,另一个带有 POST 请求。在前端,我使用 axios 来执行请求。 两个 api 调用都适用于 Postman。
我从后端创建了一个过滤器,允许将一些标头作为“Access-Control-Allow-Origin”添加到服务器响应中。
public class MyFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers",
"CSRF-Token, X-Requested-By, Authorization, Content-Type");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"POST, GET, PUT, DELETE, OPTIONS, HEAD");
}
}
我使用了 ResourceConfig "register" 方法来注册它。 当我执行 GET 请求时,我没有问题并且我正确地获取了资源。 我的问题与 POST 请求有关,因为执行时出现以下错误:
第一个错误说 "No Access-Control-Allow-Origin header is present in the requested resource" ,尽管它包含在我的响应中,我可以看到使用 Postman(此外GET 请求有效)。
我尝试向此处暴露的对应假 API 执行 POST 请求 https://reqres.in/,它们可以正常工作。
这是 axios POST: 2
axios.post("http://localhost:8089/tec/resource",this.surveyValues)
surveyValues 是一个 javascript 对象。
这是后端的资源:
@Path("resource")
public class Resource {
@Context
private Configuration configuration;
CoreEngine coreComputation;
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ResponseBody getIt(JsonSurvey survey) {
Map<String,Double> initAssessmentMap = new HashMap<String,Double>();
ObjectMapper mapper = new ObjectMapper();
CollectionMongoDB mongoDB = new CollectionMongoDB();
mongoDB = (CollectionMongoDB) this.configuration.getProperty("mongoDB");
this.coreComputation = new CoreEngine();
initAssessmentMap = this.coreComputation.InitialComputation(survey,mongoDB);
List<SecurityControls> securityControls = null;
try {
securityControls = mapper.readValue(this.coreComputation.getSecurityControls().toString(),new TypeReference<List<SecurityControls>>() {});
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResponseBody response = new ResponseBody(securityControls, initAssessmentMap);
return response;
}
希望你能帮助我!
【问题讨论】:
-
1.我为您添加了 Java 标记,因为 2. 这可能与 axios 无关 3. 它在邮递员中工作的事实并不意味着什么,邮递员不是网页,因此没有来源跨域策略。
-
您的服务器需要正确响应在您的 POST 之前发送的 CORS 预检请求。
-
您是否在 java 中使用某种框架,可能会有所帮助。
标签: javascript java vue.js axios cors