const express = require('express');
const router = express.Router();
const axios = require("axios");
var FormData = require('form-data');
var data = new FormData();
router.post('/someroute', async (req, res) => {
try {
data.append("ImageFiles", req.files.ImageFiles) // in ImageFiles storing signle object
const result = await axios({
method: 'post',
url: 'someurl',
headers: {'Authorization': req.headers['authorization'], ...data.getHeaders()},
data: data
}).catch((e) => console.log(e, "error"));
console.log(result);
} catch (error){
console.log(error, "error")
}
});
module.exports = router;
if i add JSON.stringify it will work, but another backend always think that it's not string.
Error stack
[0] TypeError: source.on is not a function
[0] at Function.DelayedStream.create (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modul
es\delayed-stream\lib\delayed_stream.js:33:10)
[0] at FormData.CombinedStream.append (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modu
les\combined-stream\lib\combined_stream.js:45:37)
[0] at FormData.append (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modules\form-data\l
ib\form_data.js:75:3)
[0] at C:\Users\someuser\PhpstormProjects\someuser\someproject\routes\api\proctoring\proctoring.js:18:14
[0] at Layer.handle [as handle_request] (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_mo
dules\express\lib\router\layer.js:95:5)
[0] at next (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modules\express\lib\router\rou
te.js:137:13)
[0] at Route.dispatch (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modules\express\lib\
router\route.js:112:3)
[0] at Layer.handle [as handle_request] (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_mo
dules\express\lib\router\layer.js:95:5)
[0] at C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modules\express\lib\router\index.js:
281:22
[0] at Function.process_params (C:\Users\someuser\PhpstormProjects\someuser\someproject\node_modules\exp
ress\lib\router\index.js:335:12) error
If i add JSON stringify, it will work. But it's not accurate. Please help. I sending img from backend to another backend
Related
I'm new to JS and react, but I'm attempting to pass a string to my API which will then run analysis on said string and pass back a sentiment score. However when I pass the data, whilst in my API's console the string appears in the 'body', the API states that the 'Description' is undefined, causing the API to throw an error.
api.js
const express = require('express');
const app = express()
app.use(express.json());
app.post('/', function (req, res) {
console.log('body is:', req.body);
const {description} = req.body;
console.log('Description is:', description);
var Analyzer = require('natural').SentimentAnalyzer;
var stemmer = require('natural').PorterStemmer;
var analyzer = new Analyzer("English", stemmer, "afinn");
const sentiment = analyzer.getSentiment(description.split(' '));
console.log('Sentiment is:', sentiment);
res.json(JSON.stringify({sentiment}))
})
app.listen(3000, () => {
console.log('listening on port 3000');
});
diary.js containing the post function and the api call
async function makePostRequest (diaryText) {
let payload = { Description: diaryText };
let res = await axios.post('http://localhost:3000/', payload);
let data = res.data;
console.log("This is the data returned in the post function:",data);
}
makePostRequest("testText").then(response => {
console.log("Data returned from the function call:", response);
}).then(error => {
console.error(error.response.data);
});
This is the output in the console when the above code is executed:
body is: { Description: 'testText' }
Description is: undefined
TypeError: Cannot read property 'split' of undefined
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/api.js:14:54
at Layer.handle [as handle_request] (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/layer.js:95:5)
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:335:12)
at next (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/express/lib/router/index.js:275:10)
at /Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Users/ddavies/Desktop/Desktop Storage/programming/MSc_App/node_modules/raw-body/index.js:224:16)
Object key is sensitive, Description =/= description
const {Description} = req.body;
Whenever I run my program, this happens:
TypeError: Cannot read property 'toString' of undefined
at /home/runner/Factions-Online-Multiplayer-Clicker-Game/index.js:28:49
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
at next (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
at /home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:335:12)
at next (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/index.js:275:10)
at expressInit (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/home/runner/Factions-Online-Multiplayer-Clicker-Game/node_modules/express/lib/router/layer.js:95:5)
I've done this before, but I'm not sure why it returns this. The code where the error happens is below.
app.get("/", (req, res) => {
var cookies = cookie.parse(req.headers.cookie.toString());
var accounts = loadjson('passwords.json');
if (cookies.username && cookies.password) {
if (cookies.username in accounts) {
if (accounts[cookies.username] === sha256(cookies.password)) {
res.render("html/game")
} else {
res.render("html/index");
}
} else {
res.render("html/index");
}
} else {
res.render("html/index");
}
});
The full program is here.
When you use cookie-parser package as a middleware it returns cookie in req.cookies object rather than req.headers.cookie.
app.get("/", (req, res) => {
var cookies = cookie.parse(req.cookies.toString());
//... Rest of the code
}
Read more about it here
Wondering what I am doing wrong here. All i want is for the mp3 which I have wired in to be downloaded to the user.
My ideal solution would be able to add a mp3 to the front of this.
const express = require('express');
var fs = require('fs');
request = require('request');
const http = require("http");
const https = require("https");
router.get('/a/:url(*)', (req, res) =>{
res.set({
"Content-Type": "audio/mp3",
// 'Transfer-Encoding': 'chunk',
// 'Content-Disposition': 'attachment'
});
const file = fs.createWriteStream("audio.mp3");
var url = req.params.url.substr(0);
console.log(url);
https.get('https://storage.googleapis.com/ad-system/testfolder/OUTOFAREA.mp3', response => {
response.pipe(file);
});
https.get(url, response => {
response.pipe(file);
});
file.push(res);
});
module.exports = router;
error I am getting is
TypeError: file.push is not a function
at router.get (/root/adstichrplayer/server/routes/podcast.js:131:10)
at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
at next (/root/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/root/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
at /root/node_modules/express/lib/router/index.js:281:22
at param (/root/node_modules/express/lib/router/index.js:354:14)
at param (/root/node_modules/express/lib/router/index.js:365:14)
at param (/root/node_modules/express/lib/router/index.js:365:14)
at Function.process_params (/root/node_modules/express/lib/router/index.js:410:3)
at next (/root/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/root/node_modules/express/lib/router/index.js:174:3)
at router (/root/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/root/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/root/node_modules/express/lib/router/index.js:317:13)
at /root/node_modules/express/lib/router/index.js:284:7
You are trying to use .push on a Writeable stream. Only streams that implement a Readable interface can call .push.
If you don't specifically need to persist the file to disk, there's no reason to create the WriteStream. You can pipe directly to Express' res object:
router.get('/a/:url(*)', (req, res) => {
res.set({
'Content-Type': 'audio/mp3',
// 'Transfer-Encoding': 'chunk',
// 'Content-Disposition': 'attachment'
});
const url = req.params.url.substr(0);
console.log(url);
https.get(url, mp3Response => {
// pipe response from HTTP request to Express res object
mp3Response.pipe(res);
});
});
while using node.js i am not able to insert a data to database ,i am using express.js ,mongoose but getting error which i mentioned in code as comment
Blockquote
error is
Blockquote
TypeError: Cannot read property 'name' of undefined
at insert (E:\node\website\controller\signup.js:5:25)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at next (E:\node\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\node\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at E:\node\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\node\website\node_modules\express\lib\router\index.js:174:3)
at router (E:\node\website\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\node\website\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
at E:\node\website\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
at query (E:\node\website\node_modules\express\lib\middleware\query.js:45:5)
Blockquote
//controller file named as signup.js
var express=require('express');
var post1=require('../model/singup')
var router=express.Router();
var insert=(req,res)=>{
var name1= req.body.name;// error:name is not defined
var email1= req.body.email;//error:email is not defined
var password1= req.body.password;//error:password is not defined
post1.create({
name: name1,email:email1,password:password1
},(err,result)=>{
if(err){res.json({message:'error'
})
}
else{res.json({message:'sucessful',result:result
})
}
})
}
router.post('/signup',insert);
router.get('/h',(req,res)=>{
res.json({
message:'insert'
})
console.log("insert");
})
module.exports=router;
Blockquote
//model file named as signup.js
require('../db');
var mongoose=require('mongoose');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
name:{type:String,required:true},
email:{type:String,required:true},
password:{type:String,required:true},
},
{timestamp:true});
module.exports=mongoose.model('post1',schema);
Blockquote
//db.js file for database connection
var mongose=require('mongoose');
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");
var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
console.log("connected with db!!!");
})
Blockquote
//index.js
var app=require('./server')
var signup=require('./controller/signup')
var session=require('express-session')
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user',signup)
app.use(session({
secret:'keyboard cat ',
resave:false,
cookies:{
secrue:true
},
}))
app.all('*',(req,res)=>{
return res.json({status: 205,message: 'not found'});
})
var server=app.get('/',(req,res)=>{
req.end()
});
Seems you are missing the body-parser middleware.
$ npm i body-parser
var express=require('express');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
I followed steps which in this page
https://developers.facebook.com/docs/messenger-platform/quickstart
My nodejs codes
app.post('/webhook/', function(req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: ");
}
}
res.sendStatus(200);
});
And I get an error like this
TypeError: Cannot read property 'entry' of undefined
at /home/user/public_html/app/testbot/webhook.js:31:30
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/user/public_html/app/testbot/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
at /home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:330:12)
at next (/home/user/public_html/app/testbot/node_modules/express/lib/router/index.js:271:10)
at serveStatic (/home/user/public_html/app/testbot/node_modules/express/node_modules/serve-static/index.js:74:16)
at Layer.handle [as handle_request] (/home/user/public_html/app/testbot/node_modules/express/lib/router/layer.js:95:5)
I can't get POST requests which coming from Facebook. How can I solve that?
I was stuck before with the same problem. You need to use the body-parser lib:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json();
then pass it to the post hook
app.post('/webhook/', jsonParser, function(req, res) {