Ionic 6 Http Post shows unknown error in normalizedNames for capacitor project - wordpress

I am calling my Wordpress REST JSON API in my Ionic Capacitor Project.
But i am getting the error shown in image below.
Ionic Capacitor HTTP Error
This is my code
const httpHeader = { // constant for http headers
headers : new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*'
})
};
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}
private dataExtract(res: Response){ // This method extract data from the request response
const body = res;
return body || {};
}
private errorHandler(error: HttpErrorResponse){ // Method for error handler
console.error(error.error instanceof ErrorEvent?`Error message:
${error.error.message}`:`Error status: ${error.error.data.status} Body: ${error.error.message}`);
return throwError(`${error.error.message}`);
}
When i call the createComment function it shows error see in image above. I have tried enable CORS with cordova-plugins-whitelist but still it shows error.
But this api is working fine in postman. I am using this in postman.
URL: https://www.readymadecode.com/wp-json/wp/v2/comments/create
Method: POST
Body: {
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
}
Please help how can i solve this error.

after try all the methods available on google, i able to solve this issue by simply removing the httpHeader from the api.
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}

Related

NgRok not reading method

node js, and ngRock, it seems that ng rock is not receiving the GET method every time i make a GET request the method deployed in ngrok is OPTIONS /category, instead of GET / category.
picture
and im not getting any response from the server
react fetch
try {
const response = await fetch(global.config.Node_API + 'categorias', {
method: 'GET'
});
if (!response.ok) {
throw new Error(`Error!, Fallo en la coneccion`);
}
const result = await response.json();
this.setState({cont:1,categor: result});
} catch (err) {
console.log(err.message);
}
in the console im getting error
Access to fetch at 'https://5833-45-229-42-135.ngrok.io/categorias' from origin 'http://localhost:3001' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
in nodeJs im using
app.use(cors())

Grab response message from .NET Core API with ky

I use ky package for sending HTTP requests to web api. Everything works except handling error messages.
Let me show you my source code:
// api method
[HttpPost("Test")]
public async Task<IActionResult> Test([FromBody] TestViewModel model)
{
if(model.Test)
{
return StatusCode(StatusCode.Status200OK, "Success message");
}
else
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error message");
}
}
My aim is get and display Success message or Error message text on the frontend.
Client side:
//webclient.js
import ky from "ky";
export const webclient = ky.create({
prefixUrl: "http://localhost:62655/api",
});
Firing API call:
//testAPI.js
import { webclient } from '../../common/webclient';
const result = await webclient.post('Order/Test', { json: { ...model } }).json();
console.log(result);
If the status code is equal to 200 the message (Success message) show in console properly, but for 500 (or 400, or any else) console remains empty.
DevTools confirm that API returns 500 status code with message Error message so it's not an API problem.
The question is: how can I obtain an error message with ky?
The ky library doesn't seem very mature but I did find this issue thread which might help ~ https://github.com/sindresorhus/ky/issues/107#issuecomment-476048453
I would strongly suggest you just stick to vanilla fetch where you're in full control of handling the response text if required
const response = await fetch("http://localhost:62655/api/Order/Test", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({ ...model })
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
console.log(await response.json())

Angular HttpClient calls are missing query string and Authorization header

When Angular makes a GET call using HttpClient, the query parameters and Authorization header are missing on the request in our QA environment. When running Angular locally, pointed to the QA APIs, it sends them both as expected.
Here's how the query parameters are set:
const params = new HttpParams().set('schedulingOnly', schedulingOnly ? 'true' : 'false');
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', { params });
Here's how the Authorization header is set (interceptor):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
const request = request.clone({
headers: request.headers
.set('Authorization', 'Bearer ' + sessionStorage.getItem('access_token'))
});
return request;
}
Here's what Chrome dev tools is showing:
That's all the basic information, but below is additional information about things I've tried without success.
Is this a CORS issue? - While searching for others with this issue, I came across a lot of CORS issues. I do not believe that's the case here because Angular and the APIs are on the same domain and I can run Angular locally and hit the APIs no problem.
Do query params get sent if I hardcode them into the url? - Yes. The following worked for the query params: return this.httpClient.get(this.getBaseUrl() + '/domain/getAll?schedulingOnly=true');
Is this something wrong with the interceptor? - I don't believe so. Console.log() statements show all the expected points in code being hit. In fact, the request object after the interceptor adds the auth header shows it on there.
I also tried setting directly without the interceptor, but no luck.
const obj = {
headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') },
params: { 'schedulingOnly': schedulingOnly ? 'true' : 'false' }
};
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', obj);
There are no js errors in the console except the 401 error
QA web server is IIS
APIs are ASP.NET Core
Angular is embedded within an ASP.NET Web Forms project (due to migrating that legacy code into Angular incrementally)
The issue was that PrototypeJs was interfering with Angular. This led to the issue, but no warnings or errors, so it was just silently causing this issue. PrototypeJs is used in the containing ASP.NET Web Forms app that Angular is embedded into. The reason this was working locally, but not in QA is because I actually did have functionality to not load PrototypeJs if it was an Angular page, due to noticing other issues before, but that wasn't working in QA due to the site starting on a subpath, not directly on the host, so that functionality of not loading PrototypeJs wasn't working.
Have you tried with the shorter version of adding header in your interceptor:
const request = request.clone({
setHeaders: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') }
});
Interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
return request.clone({
setHeaders: {
Authorization: `Bearer ${sessionStorage.getItem('access_token')}`
}
});
return request;
}

Http post request with body parameters not working

Recently I started developing a small application in Flutter. I have an issue with making a network request. I have tried the call in postman and there it work. But in Flutter I never managed to make it work, I have spent like 3 hours trying to understand what I am doing wrong.
Any help will be greatly appreciated.
#override
Future<String> login(common.LoginParameters loginParameters) async {
try {
final String loginURL = "https://test.example.eu/api/login";
LoginModel loginResult;
Map bodyParams = { "inlognaam" : loginParameters.username , "wachtwoord" : loginParameters.password, "code" : loginParameters.smsCode};
//await API call
http.Response httpResponse = await http.put( loginURL, body: json.encode(bodyParams));
if (httpResponse.statusCode == 200) {
// If server returns an OK response, parse the JSON
loginResult= LoginModel.fromJson(json.decode(httpResponse.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
// if logged in get token, Otherwise return error
if (loginResult.ingelogd) {
// read the token
saveToken(loginResult.response);
return "Ingelogd";
} else {
return loginResult.error;
}
}
on Exception catch(error) {
print("Todor " + error.toString());
return "Controleer uw internet verbinding en probeer opnieuw";
}
}
In Postman if I select Post request with body parameters
inlognaam : someUsername
wachtwoord : somePassword
code : someCode
Then I get a success response
I pass the parameters in the following way, maybe it can work for you:
var response = await http.post(
url,
headers:{ "Accept": "application/json" } ,
body: { "state": 1}, //key value
encoding: Encoding.getByName("utf-8")
);
Another thing, you say that in postman you make a post request, but in your code you have a put request, verify what is the correct method

How to show body of a bad request response in angular 4?

To provide login error message I added a message in the constructor of Bad Request Response which shows in the postman while testing an web api.
Like this: return BadRequest("Error Message");
Now I want to get that message and display in a component in the client side. But I don't know how to retrieve that. I am trying like this:
signIn() {
this.authService.login(this.loginCredentials).subscribe(result=>{
if(result){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl');
this.router.navigate([returnUrl||'/']);
}
},
(err) => {
this.loginMessage=true;
console.log(err.body);
this.invalidLogin=true;
});
}
Finally got it. It will be
console.log(err.body);

Resources