Код: Выделить всё
30
CORS Filter
com.thetransactioncompany.cors.CORSFilter
cors.allowOrigin
*
cors.supportedMethods
GET, HEAD, POST, OPTIONS
cors.supportedHeaders
*
cors.exposedHeaders
*
CORS Filter
/*
Код: Выделить всё
package com.intteinolo.resources;
import com.intteinolo.businessRules.security.SecurityModule;
import com.intteinolo.database.mongoDB.MongoDBObject;
import com.intteinolo.platformConfigutation.ApplicationConfiguration;
import com.intteinolo.platformConfigutation.DatabaseConfigConnection;
import com.intteinolo.utilities.Enumerations;
import com.intteinolo.utilities.JSonAnswer;
import com.intteinolo.utilities.JSonField;
import com.intteinolo.utilities.Util;
import jakarta.enterprise.context.RequestScoped;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.OPTIONS;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.io.File;
import java.io.InputStream;
import org.bson.types.ObjectId;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
/**
*
* @author intteinolo
*/
@Path("utilities")
@RequestScoped
public class UtilitiesResources {
@Context
private UriInfo context;
public UtilitiesResources() {
}
@OPTIONS
@Produces(MediaType.APPLICATION_JSON)
@Path("aboutOf")
public Response aboutOf() {
JSonAnswer jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.OK, "aboutOf");
jsonAnswer.addCallDataItems(
new JSonField("author", "Ing. Carlos Eduardo Rodríguez López"),
new JSonField("organization", "Intteinolo Proximity Solutions, LLC 2023"),
new JSonField("email", "info@intteinolo.com.mx")
);
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.entity(jsonAnswer.toJson())
.type(MediaType.APPLICATION_JSON)
.build();
}
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("loadFile")
public Response loadFile(
// @HeaderParam("token") String token,
@FormDataParam("files") InputStream uploadedInputStream,
@FormDataParam("files") FormDataContentDisposition fileDetail) {
JSonAnswer jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.EMPTY);
Util.getDate();
// if (SecurityModule.isTokenValid(token)) {
if (uploadedInputStream == null || fileDetail == null) {
jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.ERR, "Invalid form data.");
return Response
.status(Response.Status.BAD_REQUEST)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.entity(jsonAnswer.toJson())
.type(MediaType.APPLICATION_JSON)
.build();
}
String uploadedFileLocation = Util.documentsPath + "/" + fileDetail.getFileName();
if (!Util.writeToFile(uploadedFileLocation, uploadedInputStream)) {
jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.ERR, "Can not save file " + fileDetail.getFileName(), new JSonField("uploadedFileLocation", uploadedFileLocation));
return Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.entity(jsonAnswer.toJson())
.type(MediaType.APPLICATION_JSON)
.build();
} else {
jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.OK, "File " + fileDetail.getFileName() + " loaded.", new JSonField("uploadedFileLocation", uploadedFileLocation));
}
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.entity(jsonAnswer.toJson())
.type(MediaType.APPLICATION_JSON)
.build();
// } else {
// jsonAnswer = new JSonAnswer(Enumerations.CallStatusEnum.WRN, "Invalid token or session has expired!");
// return Response
// .status(Response.Status.UNAUTHORIZED)
// .header("Access-Control-Allow-Origin", "*")
// .header("Access-Control-Allow-Headers", "*")
// .header("Access-Control-Allow-Credentials", "true")
// .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
// .header("Access-Control-Max-Age", "1209600")
// .entity(jsonAnswer.toJson())
// .type(MediaType.APPLICATION_JSON)
// .build();
// }
}
}
Вот Angular Call для «about», apiURL — это URL-адрес инструментов веб-сервиса.
Код: Выделить всё
aboutOf(): Observable {
return this.http
.options(this.apiURL)
.pipe(retry(1), catchError(this.handleError));
}
Код: Выделить всё
uploadFile(
formData: FormData
): Observable {
console.log("UTL: ", this.apiURL + '/loadFile');
return this.http.post(this.apiURL + '/loadFile', formData, {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'false',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers':
'Origin, Content-Type, Content-Range, Content-Disposition, Content-Description, Accept, X-Custom-Header, Upgrade-Insecure-Requests, File-Name',
"Access-Control-Expose-Headers": "xsrf-token",
// appName: environment.appName,
// token: token,
}),
reportProgress: true,
observe: 'events',
});
}
Доступ к XMLHttpRequest по адресу «http://localhost:8080/SmartICMWS/resour ... s/loadFile» 'из источника 'http://localhost:4200' заблокирован политикой CORS: ответ на предполетный запрос не проходит проверку контроля доступа: в запрошенном ресурсе отсутствует заголовок 'Access-Control-Allow-Origin'.< /p>
Я не знаю, как это исправить... рабочие приложения Angular находятся в проекте Firebase, а веб-сервисы Java находятся в другом URL-адресе, размещенном на веб-сервере Payara.
Мне очень нужна помощь, я перепробовал множество возможных решений, которые прочитал в Интернете.
Подробнее здесь: https://stackoverflow.com/questions/785 ... s-im-stuck