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;
Related
const express = require('express');
const upload = require("express-fileupload");
const editJsonFile = require("edit-json-file");
const fs = require('fs');
const app = express();
app.use(upload())
app.use(express.urlencoded({ extended: true }))
const playlist = editJsonFile(`${__dirname}/playlist.json`);
app.post("/upload", (req, res) => {
//Save file from the html form to ./mp3
var file = req.files.file;
req.pipe(fs.createWriteStream("./mp3/" + file.name));
res.send("File uploaded");
playlist.append("playlist", file.name)
playlist.save()
}),
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
let html = "";
for (let i = 0; i < playlist.length; i++) {
html += `<br>${playlist[i]}`;
}
res.send(html);
}),
Hey,
Im trying to make a music player, but somehow I get the error:
ReferenceError: Cannot access 'playlist' before initialization
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\index.js:20:17
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:280:10)
at urlencodedParser (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\body-parser\lib\types\urlencoded.js:91:7)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
I can write to the Database without any issues, but when I try to read from it I get the error above, what can I do?
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
The second line console.log(playlist.get("playlist")) is trying to print the playlist variable but its declared in the next line, hence no access to that particular variable ergo the error. You can only access something after it has been initialized.
I think you are overwriting the playlist variable. The file is playlist and when you get the element you assign it to playlist as well
Also, a file is not a database
I tried following this twilio article:
https://www.twilio.com/blog/parsing-an-incoming-twilio-sms-webhook-with-node-js
The following is my server in its entirety
// Imports
const http = require('http')
const express = require('express')
const app = express()
const port = 80
const MessagingResponse = require('twilio').twiml.MessagingResponse;
// Static Files
app.use(express.static('public'))
// Set views
app.set('views', './views')
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
// Access the message body and the number it was sent from.
console.log(req.IncomingMessage.body)
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
// Listen on port
app.listen(port, () => {
console.log(`Running on port ${port}`)
})
I have the webhook of my twilio phone posting to "http://{domain}.com/sms"
Every time I send a text to my twilio phone, I get the following error:
TypeError: Cannot read property 'body' of undefined
at app.post (/home/ubuntu/{domain}/server.js:24:37)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/{domain}/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/{domain}/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/{domain/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ubuntu/{domain}/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/{domain}/node_modules/express/lib/router/index.js:275:10)
at serveStatic (/home/ubuntu/{domain}/node_modules/serve-static/index.js:75:16)
at Layer.handle [as handle_request] (/home/ubuntu/{domain}/node_modules/express/lib/router/layer.js:95:5)
I don't think the req object has any property called IncomingMessage. Instead you could try:
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
So based on the twilio specs, the endpoint would look like:
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
// Access the message body and the number it was sent from.
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
Since the message body is in the req.body.Body parameter, so console logging this property will show you the message text.
First answer is correct,
console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);
but I had to make sure to set the express urlencoding or else req.body came back as undefined.
app.use(
express.urlencoded({
extended: true,
})
);
I'm not sure if this is correct but when I'm using express I use req.body.IncomingMessage
console.log(req.body.IncomingMessage)
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
Im so frustrated with this error.. before i add some file to my project, my passport works well.. but after i add some file(like controller, view) it always show this error..
here my code in passport :
var passport = require('passport')
const bcrypt = require('bcryptjs')
var LocalStrategy = require('passport-local').Strategy
const model = require('../models/model_auth')
...
passport.deserializeUser(async function (req, data, done) {
var [resFind, errFind] = await model.byid(data.id);
if (errFind) return done(null, false);
console.log('deserialize user: ',data.id)
done(null, data);
});
here my model_auth :
const mysql = require('../module/mysql_connector')
const passport = require('../module/passport')
module.exports ={
...
byid: async function(id_panel_users){
try{
await mysql.connectAsync()
var sql= "SELECT * FROM ms_users WHERE id_user="+id_panel_users+" ";
var [result,cache]= await mysql.queryAsync(sql)
await mysql.endPool()
return [result, null]
}catch (error) {
console.log(error)
await mysql.endPool()
return [null, error]
}
},
}
here the error :
Example app listening on port 3000
(node:10700) UnhandledPromiseRejectionWarning: TypeError: model.byid is not a function
at D:\magang\eweekly\app\module\passport.js:15:46
at pass (D:\magang\eweekly\node_modules\passport\lib\authenticator.js:355:9)
at Authenticator.deserializeUser (D:\magang\eweekly\node_modules\passport\lib\authenticator.js:362:5)
at SessionStrategy.authenticate (D:\magang\eweekly\node_modules\passport\lib\strategies\session.js:60:10)
at attempt (D:\magang\eweekly\node_modules\passport\lib\middleware\authenticate.js:366:16)
at authenticate (D:\magang\eweekly\node_modules\passport\lib\middleware\authenticate.js:367:7)
at Layer.handle [as handle_request] (D:\magang\eweekly\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\magang\eweekly\node_modules\express\lib\router\index.js:317:13)
at D:\magang\eweekly\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\magang\eweekly\node_modules\express\lib\router\index.js:335:12)
so whats wrong with my model or passport?? before i added files it works! :"
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);
});
});