Getting 400 bad request in Axios but in Postman status 200 - axios

I'm trying to request a Power BI API using axios.
var configReportInfos = {
method: 'get',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.DASHBOARD_ID}`,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + tokenResponse.accessToken
},
data: {}
};
let reportinfos
try {
reportinfos = await axios(configReportInfos)
tokenResponse['reportInfos'] = reportinfos
}
catch (error) {
console.log(error);
};
Actually I'm getting this error
Request failed with status code 400"
But strangely in Postman I'm getting 200 status.
I'm using same token.

I had the same problem. When l switched content-type in my app to application.json everything worked.

I faced the same issue (not in Axios) and struggled for a few hours.
I was able to make the API call from postman but from my java code I was getting a 400.
Turns out, this was a content issue. My request body had some Cyrillic content and it needed to be encoded before sending.
Postman was doing it by default and hence the requests were going through and responding with 200

I recommend to check your Request Header options in most cases some option is configured wrong.
In your case content-type seems wrong, did you try application/json in both calls.
To configure properly you can check the documentation
Content Type Configuration

Related

Uploading file to S3 in Flutter Web (with link from backend)

I'm trying to upload a file to S3 picked with the filepicker package in flutter web. The backend provides me the link to upload the file, so in theory all I need to do is a PUT request to said link. The problem I'm having is (I think) properly sending the file in the body of the request, because if I upload the file directly to S3 with postman on the provided link, it works.
The code below is what I've been working on, after several iterations. I've tried forming the file with http.MultipartFile.fromBytes but the result is the same. I've also tried to send the request with a normal http.put request, and the error there is when I put a Multipart File in the body, if I try to json.encode, I get an error that it wasn't successful, if I don't encode it, it also gives a type error.
This current code is giving and XMLHttpRequest error, which from what I understand is probably due to a CORS error, the thing is I don't understand how that could be. Any input is appreciated!
Here is the code for uploading the image to the link provided by the backend:
Map<String, String> customHeaders2 = {
"x-amz-server-side-encryption-customer-key":
"",
"x-amz-server-side-encryption-customer-algorithm": "AES256",
"x-amz-server-side-encryption-customer-key-MD5":
"",
"Content-Type": "image/png",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "*/*",
};
final request = http.MultipartRequest(
'PUT',
//body of the response from request to the backend for the link
Uri.parse(jsonDecode(response.body)["data"]["data"]),
);
request.headers.addAll(customHeaders2);
request.files.add(
http.MultipartFile(
'file',
http.ByteStream.fromBytes(file.bytes!),
file.bytes!.length,
filename: file.name,
//contentType: MediaType('application', 'octet-stream'),
),
);
await request.send().then((value) => print(value.statusCode));
Thanks!

How to send JWT token in flutter in a request header?

I'm trying to send a request to a server that requires a parameter called 'fid' sent in the header for autherization.
Here's what you can help me with.
Payload to be sent in the header 👇
{ "fid" : "Some alphaNum value", "type": "some type string" }
I would like to know how to use jwt encoding in flutter and how to use that in the header of a request to encode and send this payload across to the server for autherization. I'm planning to use HS256 algo for encoding. Since I'm new to the concept of Jwt, there might be errors in the way I asked this question. Please share your thoughts. I would also like to know how to use the secret key too -- like how to generate the key, and where in the request to send this.
Request 👇
fetchData({required String type, required String fid, String url}) async{
<How to get the json web token>
http.get(url, header : <What do I send here>);
}
you can use http or Dio package for calling API requests in flutter,
you can set headers as follows,
https://pub.dev/packages/dio
https://pub.dev/packages/http
final response = http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

How to extract header values from http response?

I am using http post to send some information and get back the response.
final response = await http.post(
Uri.parse(
"some url"
),
headers: <String, String>{
'email': email,
'callbacktoken': callbacktoken
},
);
When I run this, my execution gets stuck at this codeblock ( I tried putting a print statement in the next line) when the response coming from the backend has header values, however if I send the response with no header from the backend (I am using django at the backend) then the my program runs with no issue.
So my question is how to handle responses with headers and how to extract them?
After a little researching I finally found the issue. My custom header name had space in it "New user" because of which http was not able to parse it. After changing the name to "newuser" everything is working fine.

Error fetch image from storage with message 'Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType'

I attemp to fetch image from Firebase storage, but have error message:
Alamofire.AFError.responseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType(acceptableContentTypes: ["image/x-xbitmap", "image/jpeg", "application/octet-stream", "image/gif", "image/ico", "image/tiff", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-win-bitmap", "image/png", "image/x-ms-bmp"], responseContentType: "application/json")
My url looks like this: https://firebasestorage.googleapis.com/v0/b/####/o/executors/o4uAQa158nXTvJ5omuxqcRb0e793/products/7DDCEEAC-ED54-4910-B93D-5E40BF411B80
I can download this image via browser.
My image has MIME-type 'image/jpeg':
I found the same situation:
Response Content-Type was missing and acceptable content types
Make sure you set alamofire acceptable content types
Image Response Serializers
These hints didn't help me to fix my bug.
Version of pod:
Alamofire: 5.0.2
AlamofireImage 4.0.2
Initially I used AlamofireImage: productImageView.af.setImage(withURL: url), but it didn't work. Then I began using Alamofire. And into request I pass MIME-type image/jpeg like Content-Type:
And I decided to use this approach to fix bug, but has the same error and I don't understand why(from docs):
If you can see in error-message I have:
responseContentType: "application/json"
So does it have any side effect to fetch image? What I do wrong at all?
Link should be
https://firebasestorage.googleapis.com/v0/b/projectname/o/image.png?alt=media&token=auth_token
replace projectname , image name and token to yours
First, your request headers have nothing do with whether the response is valid, so adding image/jpeg there won't help. Second, your response is return an application/json content type, so adding image/jpeg to the acceptable content types won't help (and image/jpeg is already acceptable). (As an aside, you need to import AlamofireImage to get addAcceptableImageContentTypes to work.)
In the end, you should ensure you're getting the response you expect, as an application/json content type implies you're getting a JSON body, not an image fro your request. When I request the URL you posted, I get this JSON response:
{
"error": {
"code": 400,
"message": "Invalid HTTP method/URL pair."
}
}
So most likely you need to double check how you're supposed to be making the request.

REST API GET/POST using jquery AJAX to get node using neo4j graph database

I'm new to REST API**(is that really my REST problem?)**
I want to get all node from neo4js by using
Cypher
START n = node(*)
return n;
how do i use if i use jquery ajax POST or GET method
in doc it recommend
POST http://localhost:7474/db/data/cypher
Accept: application/json
Content-Type: application/json
In my code i write
$.ajax({
type:"POST",
url: "http://localhost:7474/db/data/cypher",
accepts: "application/json",
dataType:"json",
contentType:"application/json",
data:{
"query" : "start n = node(*) return n",
"params" : {}
},
success: function(data, textStatus, jqXHR){
alert(textStatus);
},
error:function(jqXHR, textStatus, errorThrown){
alert(textStatus);
}
});//end of placelist ajax
What's my problem?
The error alert is below
You dont say what kind of error you get, but running exactly the same code as you, I get the following error:
XMLHttpRequest cannot load http://127.0.0.1:7474/db/data/cypher.
Origin http://127.0.0.1:3000 is not allowed by Access-Control-Allow-Origin.
So I am assuming that this is the error you are experiencing.
When performing a cross-domain Ajax call, there are two options:
JSONP, which Neo4J does not support.
Cross-Origin Resource Sharing (CORS). "The basic idea behind CORS is to use custom HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail".
The OPTIONS request sent before the POST (preflight request), returns the following headers from the Neo4J REST server:
Access-Control-Allow-Origin:*
Allow:OPTIONS,POST
Server:Jetty(6.1.25)
A cruical header is missing here, namely the Content-Type header. This means that the POST request will fail when this header is sent with the POST request, which is exactly what is happening in your $.ajax() call.
The POST will succeed if you remove the following line
contentType:"application/json",
from your $.ajax() call.
This will prevent jQuery from sending the Content-Type header.