Mashape Imgur node.js image upload - node.js

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

Related

How to see cyrillic data in json use node.js restful API

I have a cyrillic data in json format and in the API I see the data like this:
stations
0
Map_code 0
NAME_IME "Bjala river - Smoljan"
NAME_CYR "���� ���� - ��. ������"
Alertlevelwebsite 1
CODENUM 1
I want to display NAME_CYR "���� ���� - ��. ������" with UTF-8 or CP_1251 encode but I don't know how..?
The code:
app.route('/stations')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
pool.query(`SELECT * FROM sel_alert_level s;`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
stations = result;
res.json({ stations })
});
});
I try to put res.set({ 'content-type': 'application/json; charset=utf-8' }); before res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate'); like this:
app.route('/stations')
.get(function (req, res) {
// omitted
res.set({ 'content-type': 'application/json; charset=utf-8' });
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
pool.query(`SELECT * FROM sel_alert_level s;`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
stations = result;
res.json({ stations })
});
});
But this not work for me..
You need to check the headers from the response (use dev tools if you're using the browser). JSON is UTF-8 by default and if you use express it should be fine, but just double check.
If that doesn't work - use res.set({ 'content-type': 'application/json; charset=utf-8' }); (Express again).

axios content type not showing in request

var request = require('request');
var options = {
'method': 'POST',
'url': 'http://',
'headers': {
},
form: {
'username': '',
'password': ''
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
transforming this to axios request:
let data = qs.stringify({ 'username': '',
'password': '' })
const options = {
method: 'POST',data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
url: '',
};
response[0] = await Axios(options).then((res) => {
console.log("res",res)
return res.data
}
).catch((err) => {
console.log("err status", err.response.status)
return err.response.data
});
gives an error and the headers shown doesnt have the url encoded:
url: '',
method: 'post',
data: 'username=&password=',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.19.2'
},
Why the content-type : url-encoded is not in the headers and only the Accept: 'application/json, text/plain, /' is showing.
You are not showing which error you are receiving but the way you are setting the Axios call seems right following the Axios documentation. So I suspect it is a problem on how you have set up your Node.js server.
If you are using Express.js v.4+, probably you forgot to set up in your server the directive to parse application/x-www-form-urlencoded content type as explained here in the official documentation.
app.use(express.urlencoded({ extended: true }))
If you are using the body-parser package you need to set up your server with:
app.use(bodyParser.urlencoded({extended: true}));

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

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!

Aurelia HTTP client not sending headers

I'm trying to send a simple HTTP GET request to an API. The API validates the request by looking at the x-access-token header.
However, even though I set the headers on the HTTP client, the header values are not sent.
Here's my DAL
import {HttpClient} from 'aurelia-http-client';
export class BarChartDAL {
constructor() {
this.token = '';
}
getBarchartData() {
console.log('this.token: ', this.token);
var client = new HttpClient()
.configure(config => {
config.withHeader('x-access-token', this.token);
config.withHeader('Content-Type', 'application/json');
});
return client.get('http://127.0.0.1:1337/colors')
.then(data => {
console.log('got datapoints from server: ', data.response);
return (JSON.parse(data.response));
})
.catch(err => {
console.log('failed to get a response');
return false;
});
}
setToken(token) {
this.token = token;
}
}
However, on the server, the header of the request just show
request.headers { host: '127.0.0.1:1337',
connection: 'keep-alive',
'access-control-request-method': 'GET',
origin: 'http://localhost:9000',
'user-agent': '',
'access-control-request-headers': 'content-type, x-access-token',
accept: '*/*',
referer: 'http://localhost:9000/',
'accept-encoding': 'gzip, deflate, sdch, br',
'accept-language': 'en-US,en;q=0.8'
}
As you can see, there's no x-access-token header
I've got a working example here, well working in the sense that it'll send an HTTP GET, and, if I remove authentication on the server, data will come back to the client.

make a post request with in node.js application

I've a node.js service with /api/authenticate endpoint. I can call this service successfully from POSTMAN with 'username' and 'password' as input (body parameters). How do I call the same services from another node.js server?
With postman I get,
body: {name: 'xxxxxx', password: 'xxxxxx' }
headers: { 'content-type': 'application/x-www-form-urlencoded',
host: 'xx.xx.xx.xx:xxxx',
connection: 'close',
'content-length': '0' }
POST /api/authenticate 200 1.336 ms - 72
Following is another nodejs application ... which makes a successful request call but doesn't have any body parameters (username and password) when it reaches to the authentication server api.
var my_http = require('http');
app.get('/makeacall', function(req, res) {
var output = '';
var options = {
body: { name: 'xxxxxx', password: 'xxxxxx' },
method: 'POST',
host: 'xx.xx.xx.xx',
port: 'xxxx',
path: '/api/authenticate',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
console.log('before request');
var req = my_http.request(options, function(response) {
console.log('response is: ' + response);
console.log('Response status code: ' + response.statusCode);
response.on('data', function(chunk) {
console.log('Data ..');
output += chunk;
});
response.on('end', function(chunk) {
console.log('Whole Data ..' + output);
});
});
req.on('error', function(err) {
console.log('Error: ' + err);
});
req.end();
console.log('444');
res.send({ message: 'View record message'});
});
From this nodejs application I get empty body on the server.
body: {}
headers: { 'content-type': 'application/x-www-form-urlencoded',
host: 'xx.xx.xx.xx:xxxx',
connection: 'close',
'content-length': '0' }
POST /api/authenticate 200 1.336 ms - 72
What am I missing? Any help is appreciated.
Using stock http library of NodeJS doesn't allow you to use that syntax.
Take a look at RequestJS as a much simpler solution. It will make your life a lot easier and allow you to use the syntax you want.
This is the solution to do it with stock Node.
https://nodejs.org/api/http.html#http_http_request_options_callback
Relevant Parts:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
And then, at the end:
// write data to request body
req.write(postData);
req.end();
But use a library unless you absolutely can't.
Are you trying to get the posted data from a form/etc?
Try using express.
npm install express -save
You can get posted data from a url with the ff:
app.post('*', function(request, response){
var post = {};
if(Object.keys(request.body).length){
for(var key in request.body){
post[key] = request.body[key];
console.log(key+'=>'+post[key];
}
}
});

Resources