with the following code I bring a report that is hosted on JasperReports Server (This works), the problem is when passing values that have % since it returns %25 in the route and generates an error, any way to solve this problem?
const express = require('express');
const axios = require("axios");
const app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.get('/prueba', function(req,res){
res.sendFile(__dirname+"/prueba.html");
});
app.post('/form-submit', async function(req,res){
try {
const url = "http://localhost:8080/jasperserver/rest_v2/reports/reports/Re013.pdf"
const params = {
AMB_OCULTO: req.body.AMB_OCULTO,
AMB : req.body.AMB,
INS : '%',
ORD_INI: req.body.ORD_INI,
ORD_FIN: req.body.ORD_FIN
}
const file = await axios.get(url, {
params: params,
responseType: "stream",
auth:{
username: "jasperadmin",
password: "jasperadmin"
}
})
res.writeHead(200,{"Content-Type":"application/pdf"})
file.data.pipe(res)
} catch (error) {
res.sendFile(__dirname+"/prueba.html");
console.log(error)
}
});
Related
When ran, I get an error saying:
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
the code:
const express = require("express");
const app = express();
const https = require("https");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",function (req,res) {
res.sendFile(__dirname + "/public/index.html")
app.use(express.static('public'));
})
app.post("/",function(req,res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const data = {
members:{
email_address: email,
status:"subscribed",
merge_fields:{
FNAME:firstName,
LNAME:lastName
}
}
}
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/";
const options = {
method:"POST",
auth:"sudolake:api_key"
}
const request = https.request(url, options, function(response){
response.on("data",function(){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
app.listen(3000, function(){
console.log("the server is up & running");
})
I know its probably something with the "const jsonData = JSON.stringify(data);" but I don't know what, its probably really stupid, thanks for any help
I am currently working on a project and there was a problem entering the mongo db input data:
app.js
const path = require('path');
const express = require('express');
const app = express();
const getAdminPannel = require('./routes/pannelRoute');
const getView = require('./routes/viewRoutes');
app.set('view engine', 'pug');
app.set('views',path.join(__dirname,'views'));
app.use(express.static(path.join(__dirname,'public')));
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use('/api/v1/services',getAdminPannel);
//Views routes
app.use('/',getView);
module.exports = app;
routes folder
pannelRoute.js
const express = require('express');
const pannelController = require('../controller/pannelController');
const router = express.Router();
router.route('/create-services')
.post(pannelController.createPannelServices);
module.exports = router;
controller folder
pannelController
exports.createPannelServices = async(req,res) =>{
try{
const createService = Service.create(req.body);
console.log(req.body)
res.status(201).json({
length:createService.lengnth,
status:"Success",
data:{
services:createService
}
});
}catch(err){
res.status(400).json({
status:'Fail',
message:'Invalid data request'
});
}
}
script.js file where I take data from input sublit action:
import {createService} from './createService';
const createServices = document.querySelector('.createServiceForm');
if(createServices){
createServices.addEventListener('submit',(el)=>{
el.preventDefault();
const form = new FormData();
form.append('serviceName',document.getElementById('servicename_create').value);
form.append('serviceDescription',document.getElementById('serviceDescription').value);
createService(form)
})
}
createService.js script file where I use axios to inser data using api link.
import "regenerator-runtime/runtime";
import axios from 'axios';
import { showAlert } from './alert';
export const createService = async(data)=>{
try{
const create = await axios({
method:'POST',
url:'http://127.0.0.1:5000/api/v1/services/create-services',
service:data
});
if(create.data.status === 'success'){
showAlert('success','Servicul a fost creeat!!!');
window.setTimeout(()=>{
location.assign('/');
}, 1500);
}
console.log(data);
}catch(err){
showAlert('error','A aparut o problema in procesul de creeare a servicului!!!');
}
}
the problem is that req.body does not return any value is empty and that error also appears
In createService.js you aren't passing the data correctly to axios.
You'll want to change it to this:
const create = await axios({
method:'POST',
url:'http://127.0.0.1:5000/api/v1/services/create-services',
data:data
});
req.body on the backend corresponds to the data field, which you weren't populating before.
Try axios.post in the createService.js
const create = await axios.post(
'http://127.0.0.1:5000/api/v1/services/create-services',
data,
{ headers: data.getHeaders() }
);
//print body response
console.log(create.data);
i am trying to send a list containing info from a form to mailchimp server,it requires a basic http authentication. When i am sending the request using curl i am able to retrieve the page, but when i run the local sever it is showing socket errors.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public/"));
app.get("/",function(req,res){
res.sendFile(__dirname+"/signup.html");
});
app.post("/",function(req,res){
console.log(req.body);
const fn = req.body.fn;
const sn = req.body.ln;
const mail = req.body.mailid;
const data ={
members: [
{
email_address: mail,
status: "subscribed",
merge_fields: {
FNAME : fn,
LNAME :sn
}
}
]
};
var url = "https://us4.api.mailchimp.com/3.0/lists/*listid*";
var jsonData = JSON.stringify(data);
var options ={
method: "POST",
auth:"*username*:*key*"
};
const request = https.request(url,options,function(response){
response.on("d",function(d){
console.log(JSON.parse(d));
});
request.write(jsonData);
request.end();
});
});
app.listen(3000,function(){
console.log("at 3000");
});
i am getting the following
error
Try to change
response.on("d",function(d){
console.log(JSON.parse(d));
});
to
response.on("data",function(d){
console.log(JSON.parse(d));
});
and make sure to end the request by specifying request.end();. Otherwise it will not stop posting to the server you have to end posting.
I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You are sending to the client an object with the form:
{
express: data
}
And when you log that on the console you see that data is an object:
{
data: [],
type: "buffer"
}
Which means that your post request inside express is returning that object.
I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You might need to config your client as to parse response as JSON.
var options = {
mimetypes: {
json: ["application/json", "application/my-custom-content-type-for-json;charset=utf-8"]
}
};
var client = new Client(options);