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
Related
I am trying to upload a file to the API, sort the numbers and then return the result in another text file that is available to download. I upload the file, and when I start the calculation I get the Internal Server Error. The API is running on port 3000 and I start the React App.js on port 3001.
Is there something I'm doing wrong?
This is the API's app.js:
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.use(bodyParser.text({ type: 'text/plain' }));
app.post('/sort', upload.single('inputFile'), (req, res) => {
console.log(req.file)
const input = req.file.buffer.toString().split('\n').map(Number);
const result = input.sort((a, b) => b - a);
const resultText = result.join('\n');
fs.writeFile('result.txt', resultText, (err) => {
if(err) throw err;
res.send('File succesfully sorted!');
});
res.set('Content-Type', 'text/plain');
res.send(resultText);
});
app.listen(3000, () => {
console.log('API is listening on port 3000');
});
This is the React App.js:
const [inputFile, setInputFile] = useState(null);
const [result, setResult] = useState(null);
const [processingTime, setProcessingTime] = useState(null);
const handleFileUpload = (event) => {
setInputFile(event.target.files[0]);
};
const startCalculation = async (event) => {
event.preventDefault();
const startTime = performance.now();
const formData = new FormData();
formData.append('inputFile', inputFile);
console.log(inputFile)
const response = await fetch("http://localhost:3000/sort", {
method: 'POST',
body: formData,
mode: 'no-cors',
});
const data = await response.text();
console.log(data);
setResult(data);
setProcessingTime(performance.now() - startTime);
};
const handleDownload = (event) => {
event.preventDefault();
const file = new Blob([result], {
type: 'text/plain'
});
const fileURL = URL.createObjectURL(file);
const link = document.createElement('a');
link.href = fileURL;
link.download = 'result.txt';
link.click();
};
The issue is on the client you are setting the input name to inputFile, however, on the backend you are telling Multer that the input name is myFile.
Change from this:
upload.single("myFile")
To this:
upload.single("inputFile")
I am trying to access req.body in express middleware in a router, however it is consoling empty req.body. However in actual data does exist. I am already using body-parser at app level but it is not working for me. Below is my code, I am trying to access req.body in authorization middleware in categories.js file
index.js
const express = require('express');
const bodyParser = require('body-parser');
//Importing Routers
const customersRouter = require('./routes/customers');
const categoriesRouter = require('./routes/categories');
const itemsRouter = require('./routes/items');
const usersRouter = require('./routes/users');
const tablesRouter = require('./routes/tables');
const ridersRouter = require('./routes/riders');
const taxtypesRouter = require('./routes/taxtypes');
const branchesRouter = require('./routes/branches');
const subscribeRouter = require('./routes/subscription');
const loginRouter = require('./routes/login');
//Importing Database Connection
//const db = require('./dbConnection');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is listening at port ${PORT}`));
app.use('/subscribe', subscribeRouter);
app.use('/login', loginRouter);
app.use('/client/:clientID/user/:userID/customers', customersRouter);
app.use('/:clientID/categories', categoriesRouter);
app.use('/client/:clientID/user/:userID/items', itemsRouter);
app.use('/client/:clientID/user/:userID/users', usersRouter);
app.use('/client/:clientID/user/:userID/tables', tablesRouter);
app.use('/client/:clientID/user/:userID/riders', ridersRouter);
app.use('/client/:clientID/user/:userID/taxtypes', taxtypesRouter);
app.use('/client/:clientID/user/:userID/branches', branchesRouter);
router file categories.js
const express = require('express');
const util = require('util');
const categoriesRouter = express.Router();
const verifyToken = require("../functions/userVarification");
const multer = require('multer');
const fs = require('fs');
var path = require('path');
//Importing Database Connection
const db = require('../dbConnection');
const query = util.promisify(db.query).bind(db);
// File Uploading through Multer
var storage = multer.diskStorage({
destination: (req, file, cb) => {
const path = `./uploads/${req.body.clientID}/categories`;
fs.mkdirSync(path, { recursive: true });
return cb(null, path);
},
filename: function (req, file, cb) {
cb(null, req.body.clientID + "_" + "Category_" + file.originalname.replace(".", "_") +"_" + Date.now() + path.extname(file.originalname)) //Appending extension
}
})
var upload = multer({ storage: storage });
function authorization(req, res, next) {
//Only Admins are allowed to add category
const roleID = parseInt(req.authData.roleID);
if (roleID !== 1) res.status(403).json({ msg: "Sorry your are not authorized to add categories" });
else {
next();
}
}
categoriesRouter.post('/', verifyToken, (req, res, next) => authorization(req, res, next), upload.single('Image'), (req, res) => {
//destructuring request body
const clientID = parseInt(req.body.clientID);
const userID = parseInt(req.body.userID);
const name = req.body.Name;
const branches = req.body.Branches;
const color = req.body.Color;
let imageSource = `uploads/${req.body.clientID}/categories/${req.file.filename}`;
const imageInPOS = req.body.ImageInPOS;
const visibilityInPOS = req.body.VisibilityInPOS;
try {
(async () => {
//Create Local Category ID
const SQL1 = `SELECT COUNT(ClientID) AS 'Categories' FROM categories WHERE ClientID = ${clientID};`;
let counter = await query(SQL1);
counter = counter[0].Categories + 1;
const localCategoryID = 'CT' + ('00' + counter).slice(-3);
//SQL for Adding Category in the database
const SQL2 = `INSERT INTO categories (CategoryID, LocalCategoryID, ClientID, CategoryName, ShowInBranches, CategoryColor, ImageSrc, DisplayInPOS, DisplayImage)
VALUES (NULL, '${localCategoryID}', ${clientID}, '${name}', '${branches}', '${color}', '${imageSource}', ${visibilityInPOS}, ${imageInPOS})`;
const addedCategory = await query(SQL2);
if(addedCategory.affectedRows > 0) {
res.status(200).json({ msg : "Category have been added"});
}
else {
res.status(500).json({ msg: "Something went wrong" });
}
})()
}
catch (err) {
res.status(500).json({ msg: "Something went wrong" });
return;
}
});
module.exports = categoriesRouter;
the body-parser module don't require to explicitly install.
Its provided under the methods express.json() and express.urlencoded().
so add
app.use(express.urlencoded({extended: true}));
app.use(express.json())
and remove
require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
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)
}
});
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.listen(3000,function(){
console.log("server is running");
})
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.post("/",function(req,res){
var url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?";
var pincode = req.body.pinCode;
url = url + "pincode=" + pincode;
var date = req.body.date;
url = url + "&date=" + date;
console.log(pincode,date);
request(url,function(err,res1,body){
res.send(body.centers);
})
})
for the above code (undefined) value is send in res.send(body.centers)
body is in json format given as below:
{"centers":[{"center_id":596215,"name":"MISSION UHC","address":"MISSION NADIAD","state_name":"Gujarat","district_name":"Kheda","block_name":"Nadiad","pincode":387002,"lat":22,"long":72,"from":"09:00:00","to":"18:00:00","fee_type":"Free"}
Try to see how body looks
request(url,function(err,res1,body) {
console.log(body);
})
If body output in terminal with double quote like :
{
"key": "value"
}
that's mean body is JSON string and you need to parsing it to object with :
body = JSON.parse(body)
Then send it :
res.send(body.centers)
GET http://localhost:5000/booksIdea/show 403 (Forbidden)
i check the token in the website https://jwt.io/ i got invalid signature so i guess why the problem came from but i ignore how to fix it
i searched abt this error and this is what i found : Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”
API GET function on front end:
import axios from 'axios'
export const ShowBooks = () => {
let token = localStorage.getItem("usertoken")
return axios.get("http://localhost:5000/booksIdea/show", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
}
backend app.js
const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
var cors = require('cors')
var bodyParser = require('body-parser')
const port = 5000
const routes = require("./routes");
const con = require('./db')
var cors = require('cors')
app.use(cors())
// database connect
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
//cookie
app.use(cookieParser())
//routes
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
here is routes
var express = require('express')
var router = express.Router()
var Controller = require('./controller')
var authController = require('./authController')
var BooksIdeaController = require('./BooksIdeaController')
router.post('/register',Controller.register);
router.post('/login',authController.login);
router.post('/booksIdea/:id',authController.verify,BooksIdeaController.addComment)
router.post('/booksIdea/addbook',authController.verify,BooksIdeaController.addBookIdea)
router.get('/booksIdea/show',authController.verify,BooksIdeaController.showBookIdea)
router.put('/booksIdea/edit/:id',authController.verify,BooksIdeaController.UpdateBookIdea)
router.delete('/booksIdea/delete/:id',authController.verify,BooksIdeaController.DeleteBookIdea)
module.exports = router;
authController
const con = require('./db');
var bcrypt = require('bcrypt');
let jwt = require('jsonwebtoken');
const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
module.exports.login=function(req,res){
var username=req.body.name;
var password=req.body.password;
con.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
bcrypt.compare(password, results[0].password, function (err, result) {
if (result == true) {
jwt.sign({user:results},'configSecret',(err,token)=>{
res.json({
token:token
})
});
// res.json({
// status:true,
// message:'successfully authenticated'
// })
} else {
res.json({
status:false,
message:"username and password does not match"
});
}
});
}
else{
res.json({
status:false,
message:"username does not exits"
});
}
}
});
}
module.exports.home=function(req,res){
res.send('hello');
}
//////
// if(password==results[0].password){
// }else{
//
// }
module.exports.verify = function verifyToken(req, res, next) {
// Get auth header value
const bearerHeader = req.headers['authorization'];
// Check if bearer is undefined
if(typeof bearerHeader !== 'undefined') {
// Split at the space
const bearer = bearerHeader.split(' ');
// Get token from array
const bearerToken = bearer[1];
// Set the token
req.token = bearerToken;
// Next middleware
next();
} else {
// Forbidden
res.sendStatus(403);
}
}
How can I fix this error? thank you in advance for your help
Check your localstorage localStorage.getItem("usertoken")
Your token can be:
missing or undefined
incorrect token - probably a typo