Why is res.header() not working in express? - node.js

I am trying to authenticate a user for login. However, I don't manage to send a response header.
Login function
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
// the following line does not seem to work properly
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(401).json({ message: "Nutzerdaten sind nicht korrekt" });
}
});
Axios plugin
$axios.onResponse(res => {
console.log(res.headers) // does not return an authorization header
if (res.headers.authorization) {
store.commit('auth/SET_TOKEN', res.headers.authorization)
}
return res
})
console.log(res.headers)
'x-powered-by': 'Express',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'content-type': 'application/json; charset=utf-8',
'content-length': '2',
etag: 'W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"',
date: 'Tue, 30 Jul 2019 12:35:00 GMT',
connection: 'keep-alive'
I would be very thankful for any kind of help!

Related

Bad Request Error Sending from Nodejs - Raw Message Missing header info

I am trying to send an email using nodejs on a vercel host.
I am getting a bad request using the sendgrid/mail api. It looks as though it is not creating the header info in the request to Sendgrid.
When I dump the message, is it just the json info i am sending.
Here is the code i am using.
const sgMail = require('#sendgrid/mail')
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
export default function (req, res) {
const mailData = {
from: 'dhook#fullonconsulting.com',
to: req.body.email,
subject: 'Message to Full On Consulting',
text: req.body.message,
html: '<div>'+req.body.message+'</div>'
}
const {
classes: {
Mail,
},
} = require('#sendgrid/helpers');
const mail = Mail.create(mailData);
const body = mail.toJSON();
console.log("======================================== ");
console.log("RAW BODY: " + JSON.stringify(body));
console.log("======================================== ");
sendMail(mailData)
.then((result) => {
console.log('Email sent...', result);
res.status(200).json({ status: 'SUCCESS' })
})
.catch((error) => console.log('Error ... ' + error.message));
}
async function sendMail(mailData) {
try {
var promise = new Promise( (resolve, reject) => {
sgMail.setApiKey(SENDGRID_API_KEY)
const msg = {
to: mailData.to, // Change to your recipient
from: mailData.from, // Change to your verified sender
subject: mailData.subject,
text: mailData.text,
html: mailData.html,
}
console.log("API KEY: " + SENDGRID_API_KEY);
console.log(JSON.stringify(msg));
sgMail
.send(msg)
.then(() => {
console.log('Email sent');
})
.catch((error) => {
console.error(error);
console.log('RECEIVED ERROR')
})
});
//promise.then( result => {
// console.log("PRomise Success ...");
//}, function(error) {
// console.log("Promise Failure...");
//});
} catch (error) {
console.log("CATCH ERROR: " + error)
return error;
}
}
Here is the Error
ResponseError: Bad Request
at node_modules/#sendgrid/client/src/classes/client.js:146:29
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 400,
response: {
headers: {
server: 'nginx',
date: 'Sat, 30 Oct 2021 13:51:20 GMT',
'content-type': 'application/json',
'content-length': '219',
connection: 'close',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
},
body: { errors: [Array] }
}
}
I was not passing the info correctly from my front-end form which was causing the issue.
You can try expanding the response.body object and look for the error messages along with the help messages that you are getting.

Push notification send fails on server with 401 error

I am developing KaiOS application with web push notification capability.
While following code works on Chrome and current Mozilla it fails on KaiOS.
NodeJS code:
const push = require('web-push');
const vapidKeys = {
publicKey: 'PUBLIC_KEY',
privateKey: 'PRIVATE_KEY',
};
push.setVapidDetails(
'valid#email.com',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const pushSub = {
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU',
keys: {
auth: 'AUTH',
p256dh: 'P256dH',
},
};
KaiOS:
failed to send notification WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
statusCode: 401,
headers: {
date: 'Thu, 25 Feb 2021 15:35:19 GMT',
'content-length': '15',
'content-type': 'text/plain; charset=utf-8',
connection: 'close'
},
body: '{"errno":"109"}',
endpoint: 'https://push.kaiostech.com:8443/wpush/v2/gAAAAABgNqjxZulGGFU-72vZJFv0avzqAZAdWd7FSwZBINZ8AvsEkxAU2J3AFcs0e4aEUIYxi8aSzCCn8ihUgof_nfLGyR8VBprtzgZEABf14rSb9RgGgwxQip6f2792pS0BcUawcerZbNstCotDYTXdNZ7jQvegfDHUEHvril1KeEeaMoi4nGk'
}
But on Mozilla (with appropriate key changes) it response is successful. Same on Chrome.
notification response: {
statusCode: 201,
body: '',
headers: {
'access-control-allow-headers': 'content-encoding,encryption,crypto-key,ttl,encryption-key,content-type,authorization',
'access-control-allow-methods': 'POST',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'location,www-authenticate',
'content-type': 'text/html; charset=UTF-8',
date: 'Wed, 24 Feb 2021 20:38:35 GMT',
location: 'https://updates.push.services.mozilla.com/m/gAAAAABgNrlLgRnDfpaVmZjc6eqnAxoXkaYkTT4nKCTI1ZIBt62hfu2l3XvGr0F8HfvW54etByCQNSX89ubyBjd2VtXOTPqfsiC4-iDBWol9q9GRwiBSgjFc2M5-avDmrRpq9eCAsxlgGCzp2sRYRqvVDAQBHa8GznLzKmDE87rWZM6ItMiLS8PN0jqiSZFYMlqooeCK53QN',
server: 'nginx',
'strict-transport-security': 'max-age=31536000;includeSubDomains',
ttl: '2419200',
'content-length': '0',
connection: 'Close'
}
}
Here is client service worker code:
self.addEventListener('push', (event) => {
console.log('push event', event);
const title = event.data.text();
event.waitUntil(self.registration.showNotification(title));
});
Any ideas, what could be a problem?
push.sendNotification(pushSub, 'hello my name is me', {
contentEncoding: 'aesgcm'
})
.then(function (res) {
console.log('notification response: ', res);
})
.catch(function (err) {
console.error('failed to send notification', err);
});
https://github.com/web-push-libs/web-push/issues/603
This server push.kaiostech.com require authorization. It allows access from KaiOS device only.

Get request works with postman but with browser

Get request sent from POSTMAN works but when sent from browser fails.
At the backend req.body is undefined even after using bodyparser middleware.
The same requet when sent from the POSTMAN works.
This is the axios call from the frontend.
await axios.get(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
This is the backend auth handler
const isAuthenticated = (req,res,next)=>{
const accesstoken = req.body.accesstoken;
console.log(req.body);
if(!accesstoken)
{
res.json({msg:"No token provided"});
}
else
{
jwt.verify(accesstoken,process.env.ACCESS_TOKEN_SECRETE,(err,decoded)=>{
if(err)
{
res.json({msg:"Invalid token"});
}
else
next();
});
}
}
These are the cors options
app.use(cors({
origin:["http://localhost:3000","http://192.168.0.86:3000"],
optionsSuccessStatus:200,
credentials:true,
allowHeaders:["Content-Type"]
}));
The method signature you are using for axios.get applies to axios.post where the second parameter is the request body. This doesn't hold true for axios.get. You can pass query paramters as second argument of axios.get. Postman is allowing you to make GET requests with body and the server is okay with that but it isn't advised to do so. For your use case of authentication, use POST.
I guess, you meant to do axios.post:
await axios.post(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});

Can't get access token by call Meteor HTTP get request

Http token request description(Doc)
URL: https://demo.tld/connect/token
HTTP Verb: POST
HTTP Headers:
Authorization: Basic base64encode(clientId:clientSecret)
Content-Type: multipart/form-data
HTTP Body:
grant_type: client_credentials
My requested code:
try {
let endCodeOfAuth = 'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64');
HTTP.post("https://demo.tld/connect/token", {
headers: {
'Authorization': endCodeOfAuth,
'Content-Type': 'multipart/form-data'
},
content: 'grant_type:client_credentials'
}, (error, res) => {
if (res) console.log("2. res", res );
else console.log("1. error", error);
});
return true;
} catch (error) {
return false;
}
Response:
statusCode: 500,
content: '',
headers: {
server: 'Kestrel',
'x-powered-by': 'ASP.NET',
date: 'Mon, 01 Jun 2020 11:54:59 GMT',
connection: 'close',
'content-length': '0'
},
data: null
}

Mashape Imgur node.js image upload

Trying to upload users image but without success.
HTML:
Front-End JS:
var fileInput = document.getElementById('gg_test_input');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append("file", file);
xhr.open('POST', '/gg_upload');
xhr.send(formData);
});
Node.js that we sending a request to:
function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if( err ) throw err;
unirest.post('http://httpbin.org/post')
.header("X-Mashape-Key", "MASHAPE_KEY")
.header("Authorization", "clientID_KEY")
.attach('file', files.file.path)
.end(function (response) {
console.log(response.status, response.headers, response.body);
});
});
}
But I get just:
403 { 'access-control-allow-headers': 'Authorization, Content-Type, Accept, X-Mashape-Authorization',
'access-control-allow-methods': 'GET, PUT, POST, DELETE, OPTIONS',
'access-control-allow-origin': '*',
'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'content-type': 'application/json',
date: 'Sat, 15 Nov 2014 10:01:20 GMT',
etag: '"********************************************"',
server: 'Mashape/5.0.5',
'x-ratelimit-requests-limit': '12500',
'x-ratelimit-requests-remaining': '12468',
'x-ratelimit-uploads-limit': '1250',
'x-ratelimit-uploads-remaining': '1248',
'content-length': '110',
connection: 'keep-alive' } { data:
{ error: 'Malformed auth header',
request: '/3/image',
method: 'POST' },
success: false,
status: 403 }
But when tested auth with this curl it is working OK:
curl -X POST --include "https://imgur-apiv3.p.mashape.com/3/image" -H "X-Mashape-Key: MASHAPE_KEY" -H "Authorization: Client-ID clientID_KEY" -F "image=#/home/user/Desktop/face.jpg"
PLEASE, what would be the unirest.post ? Do I need provide more information?
Unfortunately the Node.js example code on Mashape is wrong, you should use this:
var unirest = require('unirest');
unirest.post("https://imgur-apiv3.p.mashape.com/3/image")
.header("X-Mashape-Key", "MASHAPE_KEY")
.header("Authorization", "Client-ID CLIENT_ID")
.header("Content-Type", "multipart/form-data")
.attach("image", "/Users/example/Projects/imgur/test_image.jpeg")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
You Client ID header is malformed (compare with cURL), if you fix that then it will work

Resources