How to POST json to mocky io - javascript

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'); }
});

Related

How to send form data in a fetch request

I wrote a simple nodejs server to allow a local web page to proxy remote data by $.ajax call) and avoid CORS problems.
Everything is working but the last call: this one is a POST call with a number of form input data that I need to turn to the remote server.
The request is received by the server but it doesn't receive the form data.
The code is:
function saveDati(req, resp) {
var url = "https://www.xyz.xyz/web/call?portlet.action=saveDataForm"
fetch(url, {
method: 'POST',
mode: 'no-cors',
body: req.body,
})
.then((resp1) => {
return resp1.text()
})
.then((risp2) => {
console.log(risp2)
resp.header("Access-Control-Allow-Origin", "*");
resp.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
resp.send(risp2);
console.log(".. sent")
})
.catch((err) => console.log(err))
}
How can I send the form data correctly?
I think you need a header like this
function saveDati(req, resp) {
var url = "https://www.xyz.xyz/web/call?portlet.action=saveDataForm"
fetch(url, {
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
mode: 'no-cors',
body: req.body,
})
.then((resp1) => {
return resp1.text()
})
.then((risp2) => {
console.log(risp2)
resp.header("Access-Control-Allow-Origin", "*");
resp.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
resp.send(risp2);
console.log(".. sent")
})
.catch((err) => console.log(err))
}

NodeJS express/request: piping a POST request with body parsing issue

I'm trying to pipe a request handling by a remote server, along with the following line:
Unfortunately pipe doesn't work well with post body, could you suggest how can I solve this issue?
self.downloadPriceLists = function (req, res, next) {
const options = {
url: `http://${env.MAILER_HOST}:${env.MAILER_PORT}/getpricelist/`,
method: 'POST',
json: true, // <--Very important!!!
headers: req.headers,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
},
body: {
userID: req.user.id,
exportAsOf: req.body.exportAsOf,
activationDate: req.body.activationDate,
},
};
console.log("options:", options);
// remoteResponse :: res
// remoteBody :: body
const myReq = request.post(options, function (error, remoteResponse, remoteBody) {
res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
remoteResponse.headers.hasOwnProperty('content-disposition') && res.setHeader('Content-disposition', remoteResponse.headers['content-disposition']);
remoteResponse.headers.hasOwnProperty('content-type') && res.setHeader('Content-type', remoteResponse.headers['content-type']);
if (error) {
console.error('request fail:', error);
return res.status(500).end('Error');
}
console.log('submit successful:', remoteResponse.headers);
res.pipe(remoteBody);
});
// Handle errors
myReq.on('error', function (err) {
console.log("++++++++++++sendReq Handle errors:", err);
res.status(500).end("Error:" + err);
});
};
Should you not be piping streams and not scalar data?
res.pipe(remoteBody); does look right to me, if anything, res.pipe(remoteResponse); seems more right.
Have you considered just writing the response of the inner request to the outer one without piping? Like so res.json(remoteBody); ?

URL not fetching the data in React

I wanted to give a post request to the required URL but without proxy setting it was giving cors error, I have gone through and end up with setting the proxy but still it is taking the localhost as the URL. I have attached my proxyfile.js and my code snippet with the error below.
export function PostData(userData) {
var targetUrl = "/downloadableReport";
return new Promise((resolve, reject) => {
fetch(targetUrl, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
Accept: "application/json"
},
body: JSON.stringify({
requestData: {
userName: userData.userName,
password: userData.password
}
})
}).then(response => response.json());
});
}
This is the setupProxy.js code:
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
proxy("/downloadableReport", {
target: "http://192.168.1.220:28080/xms/abc",
changeOrigin: true
})
);
};
And this is the error:
If CORS is the problem and you are using express as the backend server,
then
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Role');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
};
and then add
app.use(allowCrossDomain);
Ditch the proxy. To me, your problem looks like, you're POSTing data to the React App itself. If you are indeed having both the API and React, in the same project, I would suggest that you split them.
If they are not indeed together, update the targetUrl to a proper url with the protocol and the domain. Like var targetURl = 'http://localhost:3000/downloadableReport.
UPDATE: I read your comment reply to Sudhir. Edit the target Url as the full path to the API var targetUrl = "http://192.168.1.220:28080/xmsreport/report/downloadableReport" and add the CORS code I have provided above to the API at 192.168.1.220:28080

Express-API POST works in Postman but not with AJAX

I want to make an AJAX call in Javascript to my ExpressJS Rest API.
However with Javascript the POST-call does not work.
In Postman the same JSON-data with the same Headers works.
This is the error in js (ajax):
cross-origion Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.10.106:8080/api/cart/. (Reason: CORS header 'Access-Control-Allow.Origin' missing)
This is the error in node.js:
SyntaxError: Unexpected token c in JSON at position 0
at JSON.parse (<anonymous>)
Cors are enabled.
Headers are set in the AJAX (Content-Type, ...)
API-Code:
const express = require('express');
const app = express();
var cors = require('cors');
app.use(express.json());
app.use(cors());
app.options('*', cors());
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/api/cart', async (req, res) => {
res.send(true);
});
app.listen(8080, () => {
console.log('Example app listening on port 8080!');
});
AJAX-Code:
$.ajax({
url:"http://192.168.10.106:8080/api/cart/",
type:"POST", //First change type to method here
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': '*/*',
'Cache-Control':'no-cache',
},
contentType: "application/json; charset=utf-8",
data:{
JSON.stringify(cart)
},
success:function(response) {
},
error:function(data, data1, data2){
console.log(data1);
alert("An Error occurred. Try again later");
}
});
I expect the post-api be executed with this ajax code.
However this is not the case. Any ideas?
I think you need to change you ajax to this:
$.ajax({
url:"http://192.168.10.106:8080/api/cart/",
type:"POST", //First change type to method here
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': '*/*',
'Cache-Control':'no-cache',
},
contentType: "application/json; charset=utf-8",
data: JSON.stringify(cart),
success:function(response) {
},
error:function(data, data1, data2){
console.log(data1);
alert("An Error occurred. Try again later");
}
});
$.ajax({
url:"http://192.168.10.106:8080/api/cart/",
type:"POST", //First change type to method here
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': '*/*',
'Cache-Control':'no-cache',
"contentType": "application/json; charset=utf-8"
},
data:{
"itemId": 1234
},
success:function(response) {
console.log(response);
},
error:function(data, data1, data2){
console.log(data1);
alert("An Error occurred. Try again later");
}
});
Replace your ajax code with above code

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

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"

Categories

Resources