Express.js Unauthorized error - javascript

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());

Related

I am not getting any CORS error on NodeJS (Works Fine with Node) but I am getting the error on React and Javascript while fetching API

NodeJs Code:
const express = require('express');
const port = 3000;
const router = express();
router.get('/', (req, res) => {
res.send('Hi');
})
var request = require('request');
var options = {
'method': 'GET',
'url': 'URL',
'headers': {
'Authorization': 'API_KEY'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
router.listen(port, function(err) {
if(err) return;
console.log('Server Up');
})
JavaScript Code:
const options = {
method: 'GET',
headers: {
'Authorization': 'API_KEY'
}
};
fetch('URL', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Error:
has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resource. If an opaque response serves your
needs, set the request's mode to 'no-cors' to fetch the resource with
CORS disabled.
Am I missing a Header in JS or is the syntax wrong?
Note: The API I call to Get request is not my own.
This may solve your problem:
Install cors and add the following line to the node server file:
router.use(cors())
If it doesn't work, remove any headers config and try again.

JSON is becoming empty upon hitting server code

I am sending a fetch request with a JSON payload from my webpage like this:
let raw = JSON.stringify({"name":"James","favourite":"books"})
var requestOptions = {
method: 'POST',
body: raw
};
let send = () => {
fetch("http://mywebsite.herokuapp.com/send", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
On the server side I am getting an empty body {}. Here is the code I use to monitor that:
app.post('/send', (req, res) => {
console.log(req.body)
})
When I send the exact same code generated with Postman to server — somehow everything works fine, and I get the correct JSON. Please help me understand why that is.
On the server, req.body will be empty until you have middleware that matches the content type in the POST and can then read the body from the response stream and populate req.body with the results.
// middleware to read and parse JSON bodies
app.use(express.json());
app.post('/send', (req, res) => {
console.log(req.body);
res.send("ok");
});
And, then on the client side, you have to set the matching content-type, so the server-side middleware can match the content-type and read and parse it:
const requestOptions = {
method: 'POST',
body: raw,
headers: {
'Content-Type': 'application/json'
},
};

Express server not sending response to client (using fetch)

I'm using express for my server side, and i'm making a post request to the server from the client, using fetch.
The data that i'm posting to the server are being sent and displayed. The data from the server's response can't be seen anywhere in the client.
Here's my code in the server side:
app.post('/info',
ensureAuthenticated, function(req,res){
console.log(req.body)
var tryFetch = {myString: 'I am working fetch'};
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(tryFetch));
})
The client side is as follows:
fetch("/info", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name : e.target.parentElement.username,
socketID : e.target.parentElement.socketID,
id : e.target.parentElement.id,
})
})
.then( (response) => {
console.log(response)
});
When i console.log() the response, the console displays:
Response {type: "basic", url: "http://localhost:4000/info", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:4000/info"
redirected: false
status: 200
ok: truestatusText: "OK"
headers: Headers
__proto__: Headersbody: (...)
bodyUsed: false
__proto__: Response
I don't know what i'm missing here, and cannot send data from the server to the client. Can anyone help me with this please? It will be much appreciated. Thank you for your time
So, i finally found out what's wrong with this case.
The problem is not on the server, but on the client and the fetch promise. Actually, what made me think that the problem was on fetch, was when i console.log(res.body) and got
ReadableStream {locked: false}
locked: false
__proto__: ReadableStream
Here's what worked for me. I replaced
.then( (response) => {
console.log(response)
});
with
.then(response => response.json())
.then((body) => {
console.log(body);
});
So in conclusion the fetch must look like this:
fetch("/info", {
method: "post",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name : e.target.parentElement.username,
socketID : e.target.parentElement.socketID,
id : e.target.parentElement.id,
})
})
.then(response => response.json())
.then((body) => {
console.log(body);
});
Now the response from the server is displayed when i console.log()
You are supposed to res.send or res.json not res.end.
res.end() is used to quickly end the response without any data.
app.post('/info',
ensureAuthenticated, function(req,res){
console.log(req.body)
var tryFetch = {myString: 'I am working fetch'};
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(tryFetch));
})
UPDATE
To return json
app.post('/info',
ensureAuthenticated, function(req,res){
console.log(req.body)
var tryFetch = {myString: 'I am working fetch'};
res.json(tryFetch);
})
Had this exact same issue using axios due to the argument I was using for .then(). The following update worked for me...
axios.post(url, userInfo)
.then((req, res) => {
console.log('Response:', res)
})
.catch(error => console.log("client Error:", error))
Instead of .then((req, res)=>{})
Updated to .then((res) => {})
axios.post(url, userInfo)
.then((res) => {
console.log('Response:', res)
})
.catch(error => console.log("client Error:", error))

How to pass auth headers in angular 7

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

HTTP Post request not sending body or param data from ionic

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());

Categories