Angular 4 Post not working when connecting to asp.net web service - asp.net

I am using Angular 4 as front-end and it's supposed to use ASP.NET web service. angular 4 http.get is getting results just fine, but when applying http.post, it is getting this error,
System.InvalidOperationException: Request format is invalid: text/plain.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
In chrome developer extensions, I am getting that the request-type is "POST" and content-type is "text/plain; charset=utf-8", so when I am using RequestOptions in angular 4 like the following, the request-type gets changed to "OPTIONS":
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions(
{
headers: headers
}
);
var body = JSON.stringify(resource);
return this.http.post(this.url, body, options)
.map(response => response.json())
.catch(this.handleError);
I think, it's not a CORS issue, because when I am using postman, and set the content-type to "application/json" there, everything is fine. But angular creates problem here. Don't know what to do.

Related

NextJS, fetch, multipart/form-data, missing boundary

I've faced with issue while proxy http request with multipart form data by NextJS. I have to send file from a client fide to next js, after that - to FastApi service.
The problem was:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: new FormData(form)
});
headers request: "Content-Type: multipart/form-data"
In order for NextJS API to parse the file, you need a header with boundary
Something like this:
multipart/form-data; boundary=----< generate boundary >
For a long time I could not figure out how to get it.
There is an exit. It is necessary not to fill in "Content-Type".
And then the browser itself will generate this header by passing the form-data.
For example:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: {},
body: new FormData(form)
});
I also noticed that the problem concerns fetch
When I used XMLHttpRequest I didn't face such problem.
Further, the header can easily be passed further to FastAPI
in API:
req.headers["content-type"]

NextJs - Use fetch() to make api call with POST method - always ERR_ABORTED 400

when I try to make api call with fetch() method and request type is POST, then I receive error in console: "POST ... ERR_ABORTED 400 (Bad request)"
btw. I have used 'no-cors' mode because api url is on different domain, I know that this is not best approach. For now I just want to make it to work and later I will deal with CORS issue that I have when mode is not set to 'no-cors'.
const res = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify({
sku: sku
}),
headers: {
'Authorization': 'Bearer ' + jwtToken,
'Content-Type': 'application/json'
},
mode: "no-cors"
});
What can be the cause why fetch() method always returns error, maybe something with the syntax? Both "sku" and "jwtToken" variables are set.
I tried it with postman and everything works fine, but when I try to make that api call inside nextjs then its not working.

Upload captured image from Phonegap app to WordPress REST API

I'm developing an app with PhoneGap (Vue, Framework7) and a WordPress backend.
I'm trying to upload a captured image to the WordPress backend through the media REST API endpoint (using axios), but I get an error back.
The image is displayed correctly in the app (using DATA_URL - base64 encoding), but when I try to upload it to the endpoint it throws an error.
const apiHost = 'https://example.com/wp-json'
let image_form_data = new FormData
// self.images[0] is the first base64 encoded image stored in a Vuex store
// self.jwToken is the JavaScript Web Token string
image_form_data.append( 'file', self.images[0] )
const imagesOptions = {
method: 'post',
url: apiHost + '/wp/v2/media',
headers: {
"Accept": "application/json",
"Content-Type": "multipart/form-data",
"Authorization": 'Bearer ' + self.jwToken,
"Content-Disposition": "attachment; filename=\"uploaded_image.png\"",
"Cache-Control": "no-cache"
},
data: image_form_data
}
axios( imagesOptions )
.then( (imgResp) => {
console.log('imgResp')
console.log(imgResp)
} )
It throws an error:
URL: https://example.com/wp-json/wp/v2/media
State: 500 Internal Server Error
Source: Network
The server is set to accept 16M file upload, so it shouldn't be a problem (but who knows?).
But I've already got error like "resource not allowed for security reasons" (bypassed with define('ALLOW_UNFILTERED_UPLOADS', true); in wp-config.php).
I could solve it earlier with a custom API endpoint and using a filereader / blob, but it is important now for me to use the "official" endpoint.
Has somebody any idea how to solve this? (I've already read a lot of posts on SO (and elsewhere), but nothing worked.)

Getting 401 on API but working with postMan

I have this API:
const url = url;
const headers = new Headers({
"Content-Type": "application/json",
"Accept": "application/json", // change to application/javascript for jsonp
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"access_token": accessToken,
"id_token": idToken,
});
const options = {
method: "GET",
headers: headers,
credentials: "same-origin",
mode: "no-cors"
};
fetch(url, options)
.then(function(response) {
console.log('-working: ',response.json());
})
.catch(function(error) {
console.log('-error: ',error);
});
Having the same API on postMan this works like a charm there but on my code I always get 401 (Unauthorized).
Also if I remove "no-cors" I get a 401 plus CORS issue
I was having the same issue.
My senior said, that CORS is not safe, so first compare the headers of both the requests.
I would suggest you use Wireshark to see the the header that is being sent from both the requests.
Steps(step 3 and 4 is for conveniently spotting your requests):
Install Wireshark.
Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
There will be many requests and responses, close extra applications.
Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by
typing ip.dst==52.187.182.185 by putting the destination address.
Tap on your request made by postman and by your call.
Compare both the headers.
In my case, I was calling the API from my react native app, and the header parameter was getting converted into lowercase automatically.
So, to correct it, I made the parameter in lowercase in backend server.
Play "Spot the difference" between the two windows and find yours.
If this doesn't work, go with setting up CORS.
CORS needed to be added as an additional header on the back end

I see the response body in chrome developer tools, but unable to retrieve it inside Front End

I am currently working in a project where I need to send a response from grails back end to ReactJs front End. I was able to send the response from grails controller using "response" but unable to extract the response body on the ReactJs side. I tried checking in the following and found null value or undefined.
response.content, response.body
I see the response I sent back from grails in chrome web developer tools "Network" tab. but unable to find out which field of response object actually has it. Any help regarding this will be highly appreciated.
My http request.
post: function(url, item) {
return fetch(baseUrl + url, {
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain'
},
method: 'post',
body: item
}).then(function(response) {
alert(response);
return response ;
});
},
grails
response << "there is an error"
Try render 'there is an error'
Or if you need to render JSON:
render [someKey: 'there is an error'] as JSON
To understand how grails controllers and views work read this simple example.
Have you tried content-type: 'application/json'

Resources