I have an api handle the request to upload file (in spring boot) as follows:
#PostMapping("/api/admin/product/{id}/upload")
public ResponseEntity<Product> postUpload(#PathVariable("id") Integer id, #RequestParam("image") MultipartFile imageFile) {
Product product = productService.findOne(id);
return new ResponseEntity<>(productService.upload(product, imageFile),HttpStatus.OK);
}
Below is a service to process my requests. How should I fix it to fit the above api?
#Injectable()
export class ProductServiceService {
private baseUrl = 'http://localhost:8080/api/admin/product';
private headers = new Headers({'Content-Type' : 'multipart/form-data', 'Access-Control-Allow-Origin' : '*'});
private options = new RequestOptions({headers: this.headers});
constructor(private _http: Http) { }
postUpload(id) {
const formdata: FormData = new FormData();
formdata.append('image', image);
return this._http.post(this.baseUrl + '/' + id + '/upload', formdata, this.options)
.map((res: Response) => res.json())
.catch(this.errorHandler);
}
errorHandler(error: Response) {
return Observable.throw(error || 'SERVER ERROR');
}
}
And this is the error after build
Thanks!
Few of my observations based on the code shared by you:
private headers = new Headers({'Content-Type' : 'application/json'});. This is wrong, Content type should be multipart/form-data
this._http.get - this should be POST
File should be associated by image request param
I am not familiar with Angular to give you an exact answer.
Update:
If your client application is another Spring Boot application then you can run Zuul proxy on your Angular JS app and map /api URL to http://localhost:8080/api. Enabling Zuul Proxy is as simple as
* Adding dependency on spring-cloud-starter-zuul in your pom
* annotating the configuration class with #EnableZuulProxy
* Adding following in the properties: zuul.routes.api.url http://localhost:8080/api
So from your client app you call the api: http://localhost:4200/api/admin/product/17/upload and your client app (using Zuul proxy) will invoke the http://localhost:8080/api/admin/product/17/upload at the server.
Related
I have to post this json data:
JSON.stringify(dataRest) is:
{"Ds_MerchantParameters":"eyJEU19NRVJDSEFOVF9BTU9VTlQiOiI3Myw4NCIsIkRTX01FUkNIQU5UX0NVUlJFTkNZIjoiOTc4IiwiRFNfTUVSQ0hBTlRfTUVSQ0hBTlRDT0RFIjoiMzUyNDM0NDM1IiwiRFNfTUVSQ0hBTlRfT1JERVIiOiIwMDAwMDAwMDA3NjUiLCJEU19NRVJDSEFOVF9JRE9QRVIiOiIxODExNzViOTBjNDM2ZDNlZDQ3ODg4OWEyMjdjNjI2Yjc0MDBiOTEyIiwiRFNfTUVSQ0hBTlRfVEVSTUlOQUwiOiIxIiwiRFNfTUVSQ0hBTlRfVFJBTlNBQ1RJT05UWVBFIjoiMCJ9","Ds_Signature":"X5IoP/ssIy+8gBFbD9znLoz4dFOH/mWRjMCaE/8kq65XJJVLywT05wVXE4Fqbbo6","Ds_SignatureVersion":"HMAC_SHA256_V1"}
To this endpoint https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST
Using RestSharp (v107) (or httpclient).
I post above data to my api LaunchRequest via ajax:
$.ajax({
method: 'POST',
url: localhost + 'api/Redsys/LaunchRequest',
contentType: 'application/json',
data: JSON.stringify(dataRest)
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.error(error.status + '\n' + error.responseText);
});
This is the api that receive the above data and launch request to the endpoint:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
string strDataRest = JsonConvert.SerializeObject(dataRest);
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(strDataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
What is wrong?
Allways receive this message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you in advance for your help.
I think one of my mistakes is serialize dataRest.
LaunchRequest should be like this:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(dataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
I don't know if the steps I follow in LaunchRequest are correct, but anyway I always get this error message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you very much again for the help you can give me.
Your issue is most probably not related to RestSharp as it looks like a connection issue between the host running your API, and the external API host.
From the other issues, I am not sure why you deserialize the object just to serialize it back. You can just do this:
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.AddJsonBody(dataRest);
You also need to avoid creating the client for each request. Create a single client instance in the controller's constructor.
It's all described in the documentation by the way.
I'm integrating Angular with Spring boot for basic CRUD application with login module.
Login module is working fine, whereas, for creation method I get: "HttpMessageNotReadableException: Required request body is missing" for that particular method.
This is for a basic login and CRUD operation app with angular 7 and spring boot.
arrNewUser: any[] = [];
url = 'http://localhost:8080/api/user-management/add';
constructor(private http: HttpClient, private router: Router) { }
private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
createUser(form: NgForm) {
this.arrNewUser = form.value;
console.log('array', this.arrNewUser);
console.log('value', form.value);
this.http.post(this.url, JSON.stringify(this.arrNewUser), this.options).subscribe((res: Response) => {
console.log('Response:--', res.status);
console.log(this.router.url);
});
}
#RestController
#RequestMapping(path="/api", method = {RequestMethod.GET, RequestMethod.POST})
#CrossOrigin(origins="http://localhost:4200")
public class ControllerClass {
#PostMapping(path="/user-management/add", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public Status addUsers(#RequestBody String data) {
.......
return status;
}
I'm able to get required output thru postman and thru localhost:4200 angular port, but not from localhost:8080 i.e., spring boot address.
I have a json file that I want to consume in my angular app via an http get request
My plan is to host the static json file in my amazon s3 bucket with public access. The problem is trying to consume it in my angular app.
getRanges() {
return this.http.get("http://publicurl.json")
.map(res => res.json(),
(error) => this.sharedAppFunctions.showToast(error)
);
}
This is failing probably because it not a json response type.
This was the solution
getRanges() {
return this.http.get("https://xxx/Ranging.json")
.map(this.extractData);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
I'm trying to perform a post request to my WebAPI controller, but there is no way to make my action to be called.
This is the action:
[HttpPost("about")]
public async Task<IActionResult> PostAbout([FromBody] PostAboutBindingModel model)
{
if (model == null || !ModelState.IsValid)
return BadRequest(ModelState);
var about = new About
{
Text = model.Text,
Date = model.Date,
Images = _jsonSerializer.Serialize(model.Images)
};
_context.Abouts.Add(about);
await _context.SaveChangesAsync();
return Created($"/api/about/{about.Version}", about);
}
The PostAboutBindingModel has only three properties: Text, Date and Images.
This is the angular2 code snippet where I perform the API call:
let model: IAbout = <IAbout>{
date: new Date(),
images: [],
text: "test"
}
let opts = jwtAuthorization();
opts.headers.append("Content-Type", "application/json");
return this.http.post("/api/about", model, opts)
.map((response: Response) => console.log("TEST", response.json()))
.catch(this.handleError);
The jwtAuthorization simply add the Authorization header:
export function jwtAuthorization(): RequestOptions {
"use strict"
if (localStorage.getItem("auth")) {
// create authorization header with jwt token
let auth: IAuth = getAuth(JSON.parse(atob(localStorage.getItem("auth"))));
if (auth && auth.access_token) {
let headers: Headers = new Headers({ "Authorization": auth.token_type + " " + auth.access_token });
return new RequestOptions({ headers: headers });
}
}
}
I've tried to specify, as body, the following things:
model
{ model }
{ model: model }
JSON.stringify(model)
JSON.stringify({ model: model })
I've tried to specify my model as a generic object (without type) too.
I've tried to perform the call with and without the Content-Type header.
None of the previous seems to work. The API action is not called and no errors are returned.
I would like to perform the request specify only model as-is if it's possible but I would be happy in any case, if it works :)
What am I missing?
EDIT
I read now that http requests in angular 2 are "lazy" so they need a subscriber (subscribe) to work.
Thanks for help
I'm begining in Angular 2 , in the first I try to get data from JSON file and show it on a table and that's done , now I want to get data from rest api so I create my Restful webservices from Entity classes , I generate the CrossOriginResourceSharingFilter ( I use netbeans and glassfish) and I get the link with JSON output , I replace the link in the api url in angular 2 but it doesn't work
this in my Angular 2 employes.service
#Injectable()
export class EmployesService {
private empsUrl = 'localhost:25176/WebApplication4/app/employes'; // URL to web api
constructor(private http: Http) { }
getEmployes (){
return this.http.get(this.empUrl)
.map(res=> res.json())
.catch(this.handleError);
}
this is my employes.component
export class EmployesComponent implements OnInit{
emps: Employe[];
error: any;
mode = 'Observable';
errorMessage :string;
constructor(private empService: EmployesService,private _elRef :ElementRef) { }
getEmployes() {
this.empService.getEmployes()
.subscribe(
employes => this.emps = employes,
error => this.errorMessage = <any>error);
}
ngOnInit() {
this.getEmployes();
this is my console Errors
zone.js:101 XMLHttpRequest cannot load localhost:25176/WebApplication4/app/employes. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
thank you for helping