Express render() doesn't work in post request - javascript

I am trying to do a redirect in a post request, but it doesn't work for me.
Here is the express.js code that should do it:
app.set('view engine','ejs');
app.use("/",express.static('public'));
app.post("/sendMovieData", async(req,res)=>{
console.log(req.body)
res.render("../view/movie-selected")
})
And also here is the fetch request.
let requestBody = {
"movieName": movie.getAttribute("data-movieName"),
"image": e.target.src,
"city": JSON.parse(localStorage.getItem("city_country")).city,
"country": JSON.parse(localStorage.getItem("city_country")).country
}
fetch('/sendMovieData', {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(requestBody)
});

Related

How do i send an updated variable from client to server with fetch?

I am trying to send a changed variable from the client to the server, but i cant figure it out. What i am trying to achiveve is that i can use it in the main.ejs.
<script>
document.getElementById("char2btn").addEventListener("click", change)
function change() {
charOneInView = "Yes"
const data = {charOneInView}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('/welcome2', options)
}
</script>
Index.js:
var charoptioneOne = "No"
router.post('/welcome2', ensureAuthenticated, function(req, res){
console.log(req.body)
res.redirect('/main');
})
router.get('/main', ensureAuthenticated, (req, res) =>
res.render('main', {
user: req.user,
charOneInView: charoptioneOne,
charTwoInView: charoptioneTwo
})
)
To me it looks like its still a object and not a changed variable, how do i fix this?
use body-parser module in backend
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
set header of request like this:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}

CoffeeScript: HTTPS Post to API, handle response

I'm new to CoffeeScript/JavaScript, but writing a script for Hubot to talk to my Ansible Tower API in Coffee. Below is my code so far:
module.exports = (robot) ->
robot.respond /deploy zabbix agent (.*)/i, (res) ->
host = res.match[1]
https = require 'https'
authbody = JSON.stringify({
username: "awx.api",
password: "example"
})
authrequest = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/authtoken/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
authrequest.end(authbody)
body = JSON.stringify({
limit: "#{host}"
})
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
})
request.end(body)
res.reply "Deploying zabbix agent to #{host}"
In the authrequest section, I post my username and password to the API and it should return in the response JSON in the following format:
{
"token": "8f17825cf08a7efea124f2638f3896f6637f8745",
"expires": "2013-09-05T21:46:35.729Z"
}
My questions is how I store the token to use as my authentication in the later requests.
You can store it in localStorage like so:
localStorage.setItem("token", "8f17825cf08a7efea124f2638f3896f6637f8745",);
and the get it when you make a request and insert in your header
const token = JSON.parse(localStorage.getItem('token'));
request = new https.ClientRequest({
hostname: "awx.example.co.uk",
port: 443,
path: "/api/v2/job_templates/35/launch/",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
'Authorization': 'Bearer ' + token
}
})
request.on('response', function (response) {
response.on('data', function (chunk) {
let json = JSON.parse(chunk);
localStorage.setItem("token", json['token']);
});
});

post with whatwg-fetch is working but no data being posted

Im having issues with a POST with "whatwg-fetch" the response is returnin as 200 but no data is passing.
this is the code on the server...
app.post('/promo', function(request, response) {
response.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
var promo = new PromoItem();
promo.imgUrl = request.body.imgUrl;
promo.name = request.body.name;
promo.description = request.body.description;
promo.category = request.body.category;
console.log('----------');
console.log(promo.name);
console.log(request.body.name);
console.log('----------');
promo.save(function(err, savedPromo) {
if (err) {
responde.status(500).send({
error: "Something happened, promo not saved !"
});
} else {
response.status(200).send("Success !");
}
});
});
both promo.name and request.body.name are returning as undefined.
The code on the client..
setPromo = () => {
const options = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
mode: 'no-cors',
body: JSON.stringify({
"imgUrl": "http://via.placeholder.com/900x200",
"name": "MI POST",
"description": "MI PRIMER POST",
"category": "Salud"
})
};
fetch('http://localhost:3010/promo', options).then(function(response) {
console.log('Status', response.status);
})
}
have manipulated the options with different values but still the same result.
any ideas?
thanks
It's possible that the data is not being parsed. In Express, POST bodies can be parsed by body-parser. There are usage examples on the Express website. Essentially, you can use the body-parser middleware like this:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
It can also be used on a per-route basis:
app.post('/promo', bodyParser.json(), function(request, response) { //...
If you are using a version of Express >= 4.16.0, bodyParser.json is available as express.json. (source)

Send JSON data to another server (PayU) using express and angular

I am trying to make a payment application with PayU and don't know how can I send JSON data to PayU server. How I can do that?? Please help me or give me some advice. I should pass the information (from body: {...} below) POST to https://secure.snd.payu.com/api/v2_1/orders
Data which I should send to PayU (body: {...})
userFactory.paypalPayment = function(payment) {
return $http({
method: 'POST',
url: "/paynow",
headers: {
'Content-Type': 'application/json'
},
body: {
"notifyUrl": "https://your.eshop.com/notify",
"customerIp": "127.0.0.1",
"merchantPosId": "145227",
"description": "Toyota",
"currencyCode": "USD",
"totalAmount": "12",
"products":{
"name": "Wireless mouse",
"unitPrice": "15000",
"quantity": "1"
},
}
});
}
return userFactory
app.js (ExpressJS)
router.post('/paynow', function(req, res){
res.setHeader('Content-type', 'application/json; charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.json({ success: true})
})
controller
app.payment = function(payment){
User.paypalPayment().then(function(data){
console.log(data.data)
if(data.data.success) {
$window.location = 'https://secure.snd.payu.com/api/v2_1/orders'
} else {
console.log('Wrong way')
}
})
}
In order to make HTTP request to another server from NodeJS application you can use request module (or request-promise-native if you prefer promises). Code might look like this:
router.post('/paynow', function(req, res){
// your code here
request({
method: 'POST',
json: { body: req.body },
uri: 'https://secure.snd.payu.com/api/v2_1/orders',
headers: { "Content-Type": "application/json" },
(err, response, body) => {
// Callback - you can check response.statusCode here or get body of the response.
// Now you can send response to user.
}
});
});

Node.js http - send GET data to server

How can I send data with GET method using https/http module? With POST everything works.
First code (GET):
var querystring = require('querystring'),
protocol = require('https');
var options = {
host: 'httpbin.org',
path: 'get',
method: 'GET',
headers: {},
port: 443
};
var data = querystring.stringify({
limit: 3
});
Object.assign(options.headers, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(data)
});
var req = protocol.request(options, response => {
response.setEncoding('utf8');
var end = '';
response.on('data', data => end += data);
response.on('end', () => console.log(end));
});
req.write(data);
req.end();
Response:
{
"args": {},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"origin": "31.0.120.218",
"url": "https://httpbin.org/get"
}
Second code (POST, I only replaced options object):
var options = {
host: 'httpbin.org',
path: 'post',
method: 'POST',
headers: {},
port: 443
};
Response:
{
"args": {},
"data": "",
"files": {},
"form": {
"limit": "3"
},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"json": null,
"origin": "31.0.120.218",
"url": "https://httpbin.org/post"
}
I will be very grateful for some help, now I don't know what I am doing wrong.
Your problem is that in a get, the query is appended to the path, as #Quy points out, get requests don't have a body. Without an understanding of how the server is set up, I would look at doing it like so:
var data = querystring.stringify({
limit: 3
});
var options = {
host: 'httpbin.org',
path: 'get?' + data,
method: 'GET',
headers: {},
port: 443
};

Categories