Here is my code:
var url = 'http://myURL';
String tokens = "good token working on postman";
var response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $tokens',
});
print('Token : ${tokens}');
print(response.body);
The problem is that the token and the api url is working well on PostMan but it looks like flutter doesn't send the token.
It returns me a web page content.
var response = await http
.get(Uri.parse('http://192.168.1.32:8000/api/users'), headers: {
'Authorization': 'Bearer ' + sharedPreferences.getString("access_token"),
});
Related
Sending request to API with authorization and other headers, its returning unauthorized. it seems like server is not getting headers while requesting. i tried different approaches to send http headers on request but failed. I tried Dio , HttpClient, Normal http request all are failed. I spent my 2 days on this thing, still not resolved. from Postman, and other mediums request is working.
Map<String,String> reqHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
"Authorization": "xxxxx",
"langapi": "en"
};
Future<MzResponseData> getHttp() async {
var dio = Dio();
dio.options.baseUrl = baseUrl;
dio.options.headers = reqHeaders;
dio.options.contentType = ContentType.parse("application/json");
Response response = await dio.get("/uri/");
print(response);
}
Try this..
final response = await dio.get(
url,
options: Options(
headers: {
'Authorization': 'Bearer $token',
},
)
);
Future<MzResponseData> getHttp() async {
var dio = await Dio();
dio.options.baseUrl = baseUrl;
dio.options.headers = Options(headers: {'Authorization': 'Bearer $token'})//add your type of authentication
dio.options.contentType = ContentType.parse("application/json");
Response response = await dio.get("/uri/");
print(response);
}
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:
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
});
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();
});
I am using Angular 2 as front end. I tried to send an Object { test: 'Hi' }.
When my http header is like this:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
I can get the content I sent on the server side using req.body.
However, when my http header is like this:
let headers = new Headers({ 'Authorization': 'Bearer ' + token });
let options = new RequestOptions({ headers: headers });
When I use req.body again, I got an empty Object {}.
My server is using Express.js, and my bodyParser is like this:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
How can I do it correctly? Thanks
You should send both headers to express:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ....'
});