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();
});
Related
For the following code:
const apolloClient = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: endpoint,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
});
I need to get endpoint and token asynchronously. How may I do this?
Thank you
You can use apollo-link-context to modify your requests. You can cache the values as shown if you don't fetch them on every request.
let token
let uri
const contextLink = setContext(async () => {
if (!token) {
token = await getTokenAsync()
}
if (!uri) {
uri = await getUriAsync()
}
return { uri, token }
});
const client = new ApolloClient({
...
link: ApolloLink.from([
contextLink,
httpLink,
])
})
The above is the preferred way of dynamically setting these parameters. Alternatively, you could just fetch the token and URI before rendering your ApolloProvider and then dynamically create your client instance based on the values.
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 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.
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);
});
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 ....'
});