react native fetch http request throw error - http

I'm trying to make http request in react native app and it throws me an error
Uncaught Error: unsupported BodyInit type
at Response.Body._initBody (index.bundle?platform=android&dev=true&minify=false:13594)
at new Response (index.bundle?platform=android&dev=true&minify=false:13765)
at XMLHttpRequest.xhr.onload (index.bundle?platform=android&dev=true&minify=false:13820)
in index.js of the app I added this line
GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest
fetch request
const headers = {};
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
let response = await fetch('https://www.saramashkim.co.il/api/get_all_product', {
method: 'GET',
headers: headers,
body: null,
})
when I check this url in POSTMAN it works fine and I get all data..

Try the code below:
var headers = {'Accept': 'application/json', 'Content-Type': 'application/json'};
fetch('https://www.saramashkim.co.il/api/get_all_product', {
method: 'GET',
headers: headers,
}).then((response) => response.json())
.then((responseJson) => {
console.log('response', responseJson);
})
.catch((error) =>{
console.error(error);
});
You can see the response is logged to console. (I've updated my answer)
repl: https://repl.it/#tejashwikalptar/samplefetchtest
Screenshot:

Related

Where is fetch getting it's endpoint value from?

I have the following code, I am using React:
// post-post
const queryDatabase = (obj, endpoint) => {
console.log(obj);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(obj)
};
console.log(endpoint);
fetch(endpoint, requestOptions)
.then(data => {return Promise.resolve(data)}
);
}
export {queryDatabase};
For some reason console.log(endpoint) prints the endpoint that I am passing in, e.g. "/users", "/profile" etc. However, fetch is trying to send to http://localhost:3000/users so when I try to manually pass in an endpoint I get an error about trying to post to http://localhost/http://localhost/users.
Where is fetch getting this default http://localhost:3000 value?
It's only doing this for POST requests.
The only environment variables are the following:
REACT_APP_AUTH0_REDIRECT_URI=http://localhost:3000
REACT_API_SERVER_URL=http://api.localhost
PORT=3000
I also have some other environment variables for Auth0, is Auth0 doing this? I've removed these variables for testing and still nothing.
The answer is to use the Request object and pass that through to fetch:
const requestOptions = new Request(serverUrl + endpoint, {
method: 'POST',
body: JSON.stringify(obj),
headers: new Headers({
'Content-Type': 'application/json'
})
});
Why bother... use axios or something else, fetch sucks.
EDIT:
Apparently not a problem with fetch. Whatever the case this is the fix.

Can't get data from HTTP GET request Nodejs and Angular2

I'm trying to get data from my local database.
local url: http://localhost:8000/
I call this in my service /getPersonalInfoData
status showing 200, but I can't see any data there.
component.ts:
var data = this.personalInfoService.getPersonalInfoData()
.subscribe(arg => this.driverData = arg);
console.log(data);
personalInfoService:
return this.http.get('/getPersonalInfoData').map((res: Response) => { console.log(res); return res; });
backend data source API(Nodejs):
routes.get('/getPersonalInfoData',personal_info_controller.getPersonalInfoData);
In personalInfoService:-
1.import { Http, Response, Headers, RequestOptions, URLSearchParams} from'#angular/http';
2.In method add this code:
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-control': 'no-cache',
Expires: '0',
Pragma: 'no-cache'
});
const options = new RequestOptions({ headers: headers });
return this.http.get(Url, options).map(res => {
return res.json();
});
Hope this will help you.

Fetch: Can you pass parameters to the server

I'm using a basic fetch to obtain data from an express server that queries the data from a database. So I want to do a login system, i want to send the user/password from the input fields with the fetch request. so i can perform the logical check to see if password matches the data in the server. and respond with the result.
Is it possible to do a fetch that can pass parameters?
Updated Code Below:
let fetchData = {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.user,
password: this.state.password
})
}
var fromServer = fetch('http://localhost:3000/', fetchData)
.then(function(response){
if( !response.ok){
throw Error (response.statusText);
}
return response.json();
})
.then(function(response) {
console.log(response);
})
.catch(error => console.log("there was an error --> " + error));
Express function
app.post('/', function(req, res){
var uname = req.body.username;
var pw = req.body.password;
console.log(uname);
console.log(pw);
});
Of course you can!
Here is an example of Fetch using a POST request:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
I've answered this question before, check this for more details:
POST Request with Fetch API?
To process the request in Express, as mentioned in your comment assuming your express server is setup to parse body requests, you can do this:
app.post('/your/route', function(req, res) {
var name= req.body.name;
var password = req.body.password;
// ...do your bidding with this data
});

Angular and Asp.net Web Api 2 token

I am working with authentication using Angular and .Net Web API 2 back end. My registration route, and other resources are working, however the login/token is not.
In postman, this request works and I get the token back:
In angular my code looks like the following:
credentials.grant_type = "password";
credentials.userName = "email#email.com";
credentials.password = "asdfasdf";
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlenconded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:58352/Token', credentials, options).map((response: Response) => {
return response.json();
});
However, I get the response:
{"error":"unsupported_grant_type"}
In Angular.js (or Angular 1) I used transformRequest to get it working.
This did the trick!
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('userName', 'email#email.com');
urlSearchParams.append('password', 'asdfasdf');
urlSearchParams.append('grant_type', 'password');
let body = urlSearchParams.toString()
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlenconded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:58352/Token', body, options).map((response: Response) => {
return response.json();
});

Ionic 2 HTTP Request Post not working

I am trying to post data to my server, but I get a 400 Error when executing. The same request works when using get. (the post request is used for a post function and I tried the get request with a get function so that is not an issue)
This is my code:
var json =
{
"test":"asdf"
}
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post("http://192.168.0.103:3000/testPost",json,headers)
.subscribe(data => {
console.log(data);
},
data =>{
console.log(data);
});

Resources