I want to access swagger API which is expecting auth credentials user/password. So I'm creating headers Object and I'm passing credentials but it still giving me 401 unauthorized error. I'm sending my request with HTTP call as below
Any help will on this.
let headers= new HttpHeaders({
'Username':'jhon',
'Password':'Jhon123'
});
http.get(url, {headers: headers})
Hi Can you try set or append. You can try set like this
apiurl = 'yoururl';
headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.set('Username', 'john')
.set('Password', 'john123');
httpOptions = {
headers: this.headers
};
this.http.get(this.apiurl,this.httpOptions);
I hope it helps
Related
I want to post a JSON to a external api from a react form. the api needs headers (username:password) to access it. I wanted to see how I would set up a form to take the inputs of a user and pass it as headers to the api then post some json. I am able to do this with cURL but Im relatively new to react and this has been causing me some problems.
If you are using fetch to make API call you can do something like :
function signIn(username, password, body) {
const options = {
method: method,
headers: new Headers({username, password}),
mode: 'no-cors'
};
options.body = JSON.stringify(body);
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data));
}
You might wanna read more about the same here
0
fetch(your_url,a_json_object) Here,json_object has one element called headers,just use your custom header in it. But most noobies forget to add the header in backend.I am showing a correct example:
front end:
fetch('fdf.api/getid',{
method:'post',
headers:{"a_custom_header":"custom_value"}
})
backend:
const express = require('express')
const app = express()
app.use(function(req,res,next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS,
PUT,PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,a_custom_header'); //notice here carefully
res.setHeader('Access-Control-Allow-Credentials', true);
next();
})
HTTP post request is not sending body or param data to the server
Forgive me if this turns out to be a duplicate question. I've looked at several similar questions on stack overflow, but none of them have solved my problem. Also tried using a GET request instead of a POST request, but body data is still not sending.
Client side code:
// ionic code
homeUrl: string = 'http://localhost:80';
let obj = {"name": "Guest"};
let response = this.httpClient.post(this.homeUrl + '/admin-signup', JSON.stringify(obj));
response.subscribe(data => {
console.log('response: ', data);
//TODO: handle HTTP errors
});
Server side code:
server.post('/admin-signup', (req, res) => {
console.log('sign')
console.log(req.body);
// TODO: Process request
res
.status(200)
.send(JSON.parse('{"message": "Hello, signup!"}'))
.end();
});
First of all, import http client
import { HttpClient, HttpHeaders } from '#angular/common/http';
Then do the following
const header = new HttpHeaders({
'Content-Type': 'application/json',
Accept: 'application/json'
//api token (if need)
});
const options = {
headers: header
}
let response = this.httpClient.post(this.homeUrl + '/admin-signup', obj, options);
response.toPromise().then(data => {
console.log('response: ', data);
//TODO: handle HTTP errors
}).catch((err) =>{
console.log('error', err);
});
Hope it solve your problem.
I'm not familiar with ionic
but I'm guessing its a cors issue
can you try use cors?
const cors = require('cors');
app.use(cors());
I'm sending an auth token in my request headers to an Express.js API, when I make the request in postman with a header named 'Authorization' it works perfectly but when I send it with angular 4 like so:
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', `${token}`);
this.http.get<Response>(`${this.apiURL}dashboard/`, { headers: headers })
.subscribe(res => console.log(res));
When logged the headers object looks to be setting them correctly however when I try to retrieve the token in my express route like so:
const token = req.get('Authorization');
It is always undefined. What is angular doing differently from postman?
Result when I try to log the token:
Postman working:
HttpHeaders objects are immutable. Check out https://angular.io/api/common/http/HttpHeaders
Try setting headers like this
let headers = new HttpHeaders();
headers = headers.set('Authorization', 'token');
Try setting headers like this
For Angular versions < 5
import { Http, Headers, RequestOptions } from "#angular/http";
// inside your Class
headers = new Headers({
"Content-Type": "application/json",
"Accept": "q=0.8;application/json;q=0.9",
"Authorization": "token"
});
options = new RequestOptions({ headers: this.headers });
and pass this.options along with your http request.
For Angular version 5
import { HttpClient } from '#angular/common/http';
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
and pass httpOptions along with your http request.
So I found the answer, contrary to the express.js docs telling me to use: req.get('Authorization') I found that if i use req.headers['Authorization'] it works perfectly
I have method
router.post('/user',passport.authenticate('jwt', { session: false }), function (request, res) {
res.send(request.user);
});
and authorization token
"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"
when i send request to this route from postman everything is working.
but when i send request from angular application with same token its throw with error unauthorized
getUser() {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
return this.http.post('localhost:8000/api/user/', {
headers
})
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));
}
Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.
your code will be like:
import { Http, Headers, RequestOptions } from '#angular/http';
getUser() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
let options = new RequestOptions({ headers: headers });
return this.http.post('https://dropali.com/api/user/',options)
.map((data: Response) => data.json())
.catch((error: Response) => Observable.throw(error.json()));
}
Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.
1.) Check at the server side you are getting the token or not.
2.) if you are not getting the token then check Developer option > Network > your request's header tag and see whether the token is going or not
3.) if not going the problem is in a front and else it can because of cross origin..
FRONT END CODE EXAMPLE
var token = localStorage.Authorization
var options = {
url: '/user',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': token
}
}
$http(options)
.then((data) => console.log(data.data))
.catch((error) => console.log(error));
if front end is ok then you should check CROSS
app.use((req, res, next) => {
res.header('Access-Control-Expose-Headers', 'Authorization');
next();
})
OR
npm install cors --save
app.use(cors());
I'm totally new to HTTP and trying to make HTTP request. Here is the API:
I construct the request like this:
let reqString = 'GET https://login.yandex.ru/info?format=json&with_openid_identity=1 HTTP/1.1\r\n' +
'Authorization: OAuth ' + this.token;
And here is the error:
Error: Invalid URI "GET%20https://login.yandex.ru/info?format=json&with_openid_identity=1%20HTTP/1.1%0D%0AAuthorization:%20OAuth%20AQAAAAAc3LKEAAQQaS1B6d6nz0B8mq_kOr-AD6M"
I'm totally new to HTTP and backend at all, please, explain what I'm doing wrong and show me the right way
Thanks in advance
The solution for my case was to create the object and make HTTP request like this:
const request = require('request');
let reqobj = {
uri: 'https://login.yandex.ru/info?format=json&with_openid_identity=1 HTTP/1.1',
headers: {
'Authorization': 'OAuth ' + this.token
}
};
request(reqobj, (error, response, body) => {...}
Thanks for help in comments