Fetch in ReactNative can not deliver the paras in body to the server - post

ReactNative provide me with fetch to send a httpRequest.The attribute of body includes my parameters which are to send to the server.But I can't get the parameters on my server.My codes are here:
fetch(`${keys.api}/login`,
{
method: 'POST',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}
).then((response) => {
if(response._bodyText == 'success') {
this.props.resetToRoute({
name: '主页',
component: Main,
hideNavigationBar: true,
});
} else {
this.cancelLogin();
}
}).catch((error) => {
console.warn(error);
this.cancelLogin();
});
And the console in my J2EE Web Server prints the message:
The httpRequest message
There is no parameter in my httpRequest(In other words,The body can not deliver any parameters),I need help.
It's dangerous to show my username and password in the url.

i have met the problem twice on jetty-8.1 on different condition
first ,you should know that it has nothing to do with react-native
fetch put the data in body to header "payload" when the client made a request.i thought jetty-8.1 does not support get data from the payload header
,change the way
Getting request payload from POST request in Java servlet will be helpful
or maybe use the websockt or XMLhttpRequest object to send a request
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString()

Related

"Only absolute URLs are supported" When fetch webhooks Nextjs

Im trying to fetch an webhooks url using Environment Variables.
here is my code
const url = process.env.WEBHOOK_URL;
const response = await fetch(
`${url}` ,
{
body: JSON.stringify({
name,
email,
message,
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}
);
But the error show up "Only absolute URLs are supported"
please help! Thank you

Post request returning 403 when trying to call IBM AppID management API /users

I'm trying to create a custom IBM AppID Management Api interface in my application.
In order to do that, I'm using IBM IAM Token Manager library to get an IAM access token.
const itm = require('#ibm-functions/iam-token-manager')
const m = new itm({
"iamApiKey": apiKey
})
m.getAuthHeader().then(token => {
console.log("this one won't work", token)
}
var headers =
{
'accept': 'application/json',
'Authorization': token,
'Content-Type': 'application/json'
};
var options =
{
url: replacedIssUrl+"/users",
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(response)
if (!error && response.statusCode == 200) {
console.log(body); //returns "body: "Forbidden"
}
}
request(options, callback)
Whenever I try to pre-register a user with the library's generated token, the callback returns Status 403 - Forbidden, but if it gets the IAM Access token directly through ibmcloud shell (ibmcloud iam oauth-tokens), it works fine.
Does anybody have any clue why this is happening? I know for a fact that the IAM Token Manager library generated access token is working, because I'm using it to get the user ID on the same code.
When something is wrong with my Access Token, it usually returns "Unauthorized", not "Forbidden".
I have no clue why this is happening.
Thanks in advance.
When passing an IAM token in the headers, App ID expects it to be preceded by the "Bearer " string :
var headers =
{
'accept': 'application/json',
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
};

Microsoft Graph sendMail doesn't work and returns NULL

I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.

Flutter HTTP Post returns 415

I have an issue with using Method.Post on my flutter app using http dart library. It seems that when I tried to post data from my WebAPI it gaves me a StatusCode 415. See my code below:
Code Login:
Future<User> login(User user) async {
print(URLRequest.URL_LOGIN);
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: {
'username': user.username,
'password': user.password
}, headers: {
"Accept": "application/json",
}).then((dynamic res) {
print(res.toString());
});
}
Code NetworkUtils:
Future<dynamic> post(String url, {Map headers, body, encoding}) async {
return await http
.post(url, body: body, headers: headers, encoding: encoding)
.then((http.Response response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception('Error while fetching data.');
}
return _decoder.convert(res);
});
}
Does anyone knew whats going on my code?
Try adding this new header:
headers: {
"Accept": "application/json",
"content-type":"application/json"
}
UPDATE
Ok now you need to send json data, like this :
import 'dart:convert';
var body = jsonEncode( {
'username': user.username,
'password': user.password
});
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: body, headers: {
"Accept": "application/json",
"content-type": "application/json"
}).then((dynamic res) {
print(res.toString());
});
}
#Alvin Quezon
I met the same error as yours and fix it, please see below.
[Error]
StateError (Bad state: Cannot set the body fields of a Request with content-type "application/json".)
[Reason]
when you use the Flutter plug 'http.dart' method 'http.post()', you should read the document in detail below (note the black fonts):
Sends an HTTP POST request with the given headers and body to the given URL.
[body] sets the body of the request. It can be a [String], a [List<int>] or
a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
used as the body of the request. The content-type of the request will
default to "text/plain".
If [body] is a List, it's used as a list of bytes for the body of the
request.
If [body] is a Map, it's encoded as form fields using [encoding]. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
[encoding] defaults to [utf8].
For more fine-grained control over the request, use [Request] or
[StreamedRequest] instead.
Future<Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
[Solution]
So just encode your body as a string ,then you can set the header 'content-type' as 'application/json'.
see the codes of #diegoveloper answered!

Posting an Asana task using fetch

I'm trying to work with the Asana API as I learn React and Redux. I've been able to get data from the Asana API using fetch() just fine so far, but I'm having trouble posting a task.
Here is the code I'm using:
const options = (type, data) => {
const defaultHeaders = {
'Authorization': `Bearer ${apiKey}`,
'Asana-Fast-Api': 'true',
}
switch(type) {
case 'get':
return {
headers: defaultHeaders,
}
case 'post':
const body = JSON.stringify(data)
console.log(body);
return {
method: 'POST',
headers: defaultHeaders,
contentType: 'application/json',
body: body,
}
default:
return {
headers: defaultHeaders,
}
}
};
const asanaUrl = (props) => {
const numOfProps = props.length;
switch (numOfProps) {
case 3:
return `https://app.asana.com/api/1.0/${props[0]}/${props[1]}?${props[2]}`
case 2:
return `https://app.asana.com/api/1.0/${props[0]}?${props[1]}`
case 1:
return `https://app.asana.com/api/1.0/${props[0]}`
default:
return console.log(props)
}
}
export const asanaPost = (props, data) => {
return fetch(asanaUrl(props), options('post', data))
.then(response => response.json() )
}
In the console, I see the return from the console.log which shows the JSON I'm sending into my body key:
{"assignee":22800770039251,"name":"test","notes":"test"}
and the following error
Failed to load resource: the server responded with a status of 400 (Bad Request)
The URL appears to be correct: https://app.asana.com/api/1.0/tasks?workspace=31542879721131
The error message is:
"Must specify exactly one of project, tag, or assignee + workspace"
It doesn't seem to matter what fields I include in the body (including a project resulted in the same error), which makes me suspect that something else is afoot and the Asana API isn't getting a hold of the body or isn't able to interpret it with how I've set things up.
Thanks for helping me out with this!
The api url I use is
https://app.asana.com/api/1.0/tasks?opt_fields=html_notes
I also pass projects as a key and a string value in the body.
I do not use 'Asana-Fast-Api': 'true' in the headers

Resources