how to remove "__proto__":{} in node.js - javascript

hi all I have a code like this
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
req.body = _.omit(req.body, '__proto__');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(req.body));
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
but it is sending me response in this FORMAT
{"{\"code\":\"Øù4\n\u0013¦é\",\"Age\":25}":"","proto":{}}
I just want remove "proto":{} or specifically to sal I want to get the output like this
"{\"code\":\"Øù4\\n\\u0013¦é\",\"Age\":25}"
will you guys please check where I am making the bug or the error
well,I am send the ajax request to the controller by this process
function encryptCode()
{
var value = document.getElementById("code").value;
var key = "secretKeyToProvide"; /*--Provide Your secret key here--*/
var codeValue = rc4(key, value);
var arr = {code:codeValue, Age:25};
var request =
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: "application/x-www-form-urlencoded", //This is what made the difference.
});
request.success(function(result) {
var value = JSON.stringify(result);
alert(value);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
how to get rid of this "proto"

Related

Express routes giving 500 internal server

my server can't find the api's that i created in api directory. it leads to 500 internal server.
I have checked routes.js but i see that everything is right. i have an error.js file for file handling. Here's my code.
'use strict';
let router = require('express').Router();
// Middleware
let middleware = require('./controllers/middleware');
router.use(middleware.doSomethingInteresting);
// Tasks
let tasks = require('./controllers/tasks');
let createkeypairs = require('./controllers/createkeypairs');
let importaddress = require('./controllers/importaddress');
let getwalletinfo = require('./controllers/getwalletinfo');
router.get('/tasks', tasks.findAll2);
router.get('/createkeypairs', createkeypairs.findAll);
router.get('/importaddress', importaddress.findAll);
router.get('/getwalletinfo', getwalletinfo.findAll);
router.post('/buggyroute', tasks.buggyRoute);
// Error Handling
let errors = require('./controllers/errors');
router.use(errors.errorHandler);
// Request was not picked up by a route, send 404
router.use(errors.nullRoute);
// Export the router
module.exports = router;
now showing you my createkeypairs.js
'use strict';
let errors = require('./errors.js');
var request = require("request");
var options = { method: 'POST',
url: '127.0.0.1:18332',
headers:
{ 'Authorization': 'Basic bXVsdGljaGFpbnJwYzpHTmJ5enJhMnlHRjN4Ymp1cnluRTFucTlnV1ExRXV3OTFpYVBqSkt5TkJxdA==',
'cache-control': 'no-cache',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json' },
body: { method: 'createkeypairs', params: [], chain_name: 'tokenchain' },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log("working here ");
// res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
I think the problem is in createkeypair file.
Try this code once for your createkeypairs.js:
'use strict';
let errors = require('./errors.js');
var request = require("request");
let config = require('config');
var auth = 'Basic ' + Buffer.from(config.user + ':' + config.pass).toString('base64');
var url = config.url;
var chain = config.chain;
var options = { method: 'POST',
url: url,
headers:
{ 'cache-control': 'no-cache',
Authorization : auth,
'Content-Type': 'application/json' },
body: { method: 'importaddress', params: ["address"], chain_name: chain },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
Do tell me if it works or not.

Is there a way for filer API endpoint JSON response?

I have an external API endpoint that uses basic authentication that I'm trying to find a specific key and/or value of from the JSON response.
Results:
hrefsOnly returns an array with two items.
[
"https://192.168.254.133/api/json/v2/types/volumes/1",
"https://192.168.254.133/api/json/v2/types/volumes/3"
]
Calling hrefsOnly[1] shows the following JSON response:
{ "content": {
"ancestor-vol-name": null,
"small-io-alerts": "disabled",
"last-refreshed-from-obj-name": null,
"small-iops": "0",
"wr-latency": "1738",
"obj-severity": "information"
}}
volumeInfo is undefined in my code is below:
const express = require('express');
const app = express();
const request = require("request");
const bodyParser = require('body-parser');
const auth = 'YWRtaW46WHRyZW0xMA==';
//Get Volume api endpoint values
var getVols = {
method: 'GET',
url: 'https://192.168.254.133/api/json/v2/types/volumes/',
headers:
{
'cache-control': 'no-cache',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Basic ${auth}`
}
};
//Get above api endpoint data
var volsData = {
method: 'GET',
url: 'https://192.168.254.133/api/json/v2/types/volumes/1',
headers:
{
'cache-control': 'no-cache',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Basic ${auth}`
}
};
var hrefsOnly = [];
var volumeInfo = [];
//GET request to parse hfref data only
request(getVols, function (error, response, body) {
var data = JSON.parse(body);
if (error){
console.log('error: ', error);
} else {
for(var i = 0; i < data["volumes"].length; i++){
hrefsOnly.push(data["volumes"][i].href);
}
}
});
app.get('/url', (req, res, next) => {
res.send(hrefsOnly);
});
// GET Volumes JSON response
request(volsData, function (error, response, body) {
var vols = body;
if (error){
console.log('error: ', error);
} else {
for(var elem in vols){
volumeInfo.push(vols);
}
}
});
app.get('/volume', (req, res, next) => {
console.log(volumeInfo["content"]);
res.send(volumeInfo["content"]);
});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
app.listen(3000, () => {
console.log("Server running on port 3000");
});
I expect when I visit the page localhost:3000/volume to return the content section from the API. the page shows blank though.
console.log(volumeInfo[1]) shows the JSON data, but volumeInfo[1].content is undefined. Not sure what I'm doing to get 'undefined' as the result.
You declared an array var volumeInfo = []; but you're using it as a map res.send(volumeInfo["content"]);
TTo access an element inside an array, you need an index (integer). Try with res.send(volumeInfo[0].content);

How to POST json to mocky io

How can JSON object be posted to a Mocky IO URL using Javascript?
I have tried:
function mocky(req, res) {
test = JSON.post(
"http://www.mocky.io/v2/5185415ba171ea3a00704eed",
{
method: "POST"
},
function (test, value, ex) {
if(value){
console.log(value);
} else {
console.log(ex);
}
}
);
}
After trying various solutions, I finally figured out the one that works like a charm!
Run the following command from the project root directory:
npm install request
//Enabling CORS on ExpressJS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content- Type, Accept");
next();
});
//Making an API call from NodeJS server
// Posting field (json object) to mocky.io
var request=require('request');
var mockyPostRequest = {
url: 'http://www.mocky.io/v2/596a5f03110000920701cd92',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: field
};
request(mockyPostRequest, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
// Logging the post data on the console
console.log(body);
}
});
I used following as the reference:
https://enable-cors.org/server_expressjs.html
Thanks everyone for replying.
Try this typical jquery ajax call-
var jsonData = {"x":"Apple", "y":"Mango"};
$.ajax({
url: 'http://www.mocky.io/v2/596a5f03110000920701cd92',
type: 'POST',
dataType: 'json',
data: jsonData,
success: function() { alert('POST completed'); }
});

Logging into Shopify using Node.js

I'm trying to post discount codes to a user's shop using the reverse engineering instructions shown here http://ma.rtin.so/reverse-engineering-shopify-private-apis (instructions are in PHP)
The first step is properly logging into the users account so I can grab information from the response. Am I doing this step correctly? I feel like I'm missing something to do with tokens, but its hard for me to understand the PHP code given in the instructions.
I am receiving a response without an error status code from the login function but I still don't know if this means I'm doing it correctly. Thanks for any help.
Node.js Discount Creation Controller (Please look at login function but included the whole thing in case)
use strict';
var request = require('request');
var cookie = require('cookie');
var USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17';
var login = function(req, res, cb) {
req.url = 'https://' + req.body.name + '.myshopify.com';
var post_data = {
'utf8': '✓',
'redirect': '',
'subdomain': req.body.name,
'login': req.body.email,
'password': req.body.pwd
}
var headers = {
'User-Agent': USER_AGENT,
'Content-Type': 'application/x-www-form-urlencoded'
};
var url = req.url + '/admin/auth/login';
request.post({ url: url, form: post_data, headers: headers }, function(err, response, body) {
if (err) 'ERROR LOGGING IN';
else {
if (response.statusCode !== 200) throw 'ERROR LOGGING IN';
console.log('Login response headers:', response.headers);
var shopCookies = response.headers['set-cookie'];
var j = request.jar();
for (var i = 0; i < shopCookies.length; i++) {
var cookie = request.cookie(shopCookies[i]);
j.setCookie(cookie, url);
}
req.cookie_string = j.getCookieString(url);
if (cb !== undefined) cb(req, res);
}
});
};
var setCoupons = function(req, res) {
var url = req.url + '/admin/discounts/new';
var headers = {
'User-Agent': USER_AGENT,
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': req.cookie_string
};
request.get({ url: url, headers: headers }, function(err, response, body) {
if (err) throw 'Problem setting coupons';
var value = response.body.match(/name="authenticity_token" value=".*"/i)[0];
var index = value.indexOf('value="');
value = (value.substring(index + 7, value.length - 1));
var count = parseInt(req.body.amount) + 1;
var checkCount = count;
var codes = [];
for (var i = 1; i < count; i++) {
var post_data = {
utf8: '✓',
authenticity_token: value,
discount: {
code: req.body.code + "_" + i,
discount_type: req.body.discount_type,
value: parseInt(req.body.value),
applies_to_resource: '',
starts_at: '2016-04-10'
},
'unlimited-uses': '',
discount_never_expires: ''
}
codes.push(post_data.discount);
var url = req.url + '/admin/discounts';
request.post({ url: url, form: post_data, headers: headers }, function(err, response, body) {
checkCount--;
if (checkCount < 2) {
res.send(codes);
}
});
}
});
};
export function create(req, res) {
login(req, res, setCoupons);
}
Discount codes are only available to Shopify Plus customers.
The API however is available now: https://docs.shopify.com/api/reference/discount
Also rather than using Shopify Plus it would be possible to create your own Discount code engine as an app and apply discounts to sales orders.

php to node.js ajax sending does not give response

I was trying to post some data from my php page to my node.js server.and I want to get the response from it.
This is the ajax code which I was sending from my php page which is currently executing on the apache server
function encryptCode()
{
var value = document.getElementById("code").value;
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(value),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
and I just want to receive it in my node.js page by this code
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(data);
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
});
This is a controller of my express.js,which I have redirected from my app.js page with this code
app.all('/insertUser', attachDB, function(req, res, next) {
insertUser.run( req, res, next);
});
will somebody please help me out in the console.log I am getting {} .....
First test is it problem with the frontend.
function encryptCode()
{
var value = document.getElementById("code").value;
console.log(value);
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: {"user":value},
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
You should set json body parser in your express app
var app = express();
bodyParser = require('body-parser');
app.use(bodyParser.json());
where did you declare data variable. In node.js the data sent through ajax request is available at req.body
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(req.body);
// console.log(req.body.user);
},
});

Categories

Resources