Can't send data through axios and node back-end - javascript

I am trying to access the expression passed from the backend to the frontend through axios.
Producer side:
const axios = require('axios');
const URL = "http://localhost:5000/"
let n1 = 3
let n2 = 5
let sum = n1+n2;
axios.post(URL, JSON.stringify({
expression: sum,
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
and on the consumer side:
const express = require('express')
const app = express()
app.post('/', (req, res) => {
console.log(req.body);
})
app.listen(5000, () => console.log())
Ultimately, I would like to have the consumer side log "8"

You don't need to convert to JSON, axios serves JSON natively.
Add to the server:
app.use(express.json())
Just send you data:
axios.post(URL, { expression: sum, })
.then(console.log)
.catch(console.err)

From the "express" documentation:
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
Try including this before you try to register the endpoint:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
You can also use express.json() and drop the 'body-parser' dependency:
// const bodyParser = require('body-parser')
app.use(express.json())

Axios have some security measures as well, you should put your IP address in
const URL = "http://localhost:5000/"

Related

Viewing JSON data sent from a Node backend to a public JS script

I have a simple backend that I'd like to return a string of data whenever a POST request is made. The string is converted to JSON, but when I see that the response was successfully received by the client (the browser), the string is missing from the response data in the browser's console.
server.js (the request handler itself is simple, there's just a few dependencies listed)
const path = require('path');
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const {createCanvas, loadImage} = require("canvas");
const cors = require('cors');
const requestIp = require('request-ip');
const { json } = require('body-parser');
const bodyParser = require('body-parser');
const wgServer = express();
const port = 3000;
const fs = require("fs");
const { createContext } = require("vm");
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.use("/public", express.static(path.join(__dirname, 'public')));
wgServer.use(bodyParser.json({limit: '50mb'}))
wgServer.listen(port, function() {
console.log(`Weatherglyph server succesfully listening on port ${port}.`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'application/json');
... Lots of functions etc irrelevant to the question
let picpath = __dirname + "\\image.png";
let picbuff = fs.readFileSync(picpath);
let picbase64 = picbuff.toString('base64');
console.log(picbase64);
res.status(201).json({picbase64});
res.send();
})})
script.js
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify({city: x});
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'application/json'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Is the data (a .png converted to base64 and sent to the frontend) actually reaching the client and I just can't see it in Chrome's console, or am I sending it incorrectly?

fetch() POST requests with Express: unexpected end of JSON input

I've been trying to practice with some HTTP requests, and specifically I want to send a POST request, with data taken from an field, and sent via fetch() to a url on my localhost thats set up with express. From there i want to somehow get the response back and have that be displayed on my HTML doc.
However, I've ran into a real head scratcher when it comes to getting response.json() to be anything other than undefined.
here's my frontend script:
const url = "/result";
const inputField = document.querySelector("#write");
const submitButton = document.querySelector("#submit");
const responseField = document.querySelector("#text-goes-here");
const postText = async () => {
const text = inputField.value;
const data = JSON.stringify({ destination: text });
try {
const response = await fetch(url, {
method: "POST",
body: data,
headers: {
"Content-type": "application/json",
},
});
if (response.ok === true) {
const jsonResponse = await response.json();
responseField.innerHTML = jsonResponse;
}
} catch (error) {
console.log(error);
}
};
const displayText = (event) => {
event.preventDefault();
while (responseField.firstChild) {
responseField.removeChild(responseField.firstChild);
}
postText();
};
submitButton.addEventListener("click", displayText);
and my server script:
const express = require("express");
const bodyParser = require("body-parser");
const read = require('fs');
const router = express.Router();
const app = express();
const port = 3000;
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.sendFile("public/index.html");
})
router.post("/result", (req, res) => {
console.log(req.body);
res.send();
});
app.use("/", router);
app.listen(port, () => {
console.log(`Server running at port: ${port}`)
});
I did some digging in the dev console and found that (response.ok) is in fact "true", yet it errors out into the catch statement saying "SyntaxError: Unexpected end of JSON input
at postText (script.js:23)"
which is this line exactly:
const jsonResponse = await response.json();
can anyone shed any light on what i'm doing wrong here? I'm at a loss at this point
This error means that you're trying to parse something that is not a valid JSON object.
"SyntaxError: Unexpected end of JSON input at postText (script.js:23)"
Which is true, because the response you're sending back to the frontend is not a JSON.
router.post("/result", (req, res) => {
console.log(req.body);
// The response is not a valid JSON object
res.send();
});
You can change res.send() to res.json() and give it a valid object.
res.json({ name:"John", age:30, car:null })

express.js get method cannot get req.body value

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

Express js bodyparser post req.body not working?

I try to build an api with express js post request. I use body-parser for req.body . But after sending post request i couldn't get any message still loading then show timeout. where is my problem please take a look my code.
I am testing it from postman and use on header content-type application/json.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config/config.js').get(process.env.NODE_ENV);
const mongoose = require('mongoose');
const app = express();
mongoose.connect(config.DATABASE)
const {Book} = require('./models/book')
app.use(bodyParser.json())
// Post Book
app.post('api/book', (req,res)=>{
let book = new Book(req.body)
book.save((err, doc)=>{
if(err) return res.status(400).send(err);
res.status(200).json({
post:true,
bookId: doc._id
})
})
})
Now error show- cannot post /api/book
but when i try with this below code its working--
const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));
Change your route from api/book to /api/book - add a leading /.
Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware.
You have passed the function:
app.use(cookieParser)
...but you need to invoke it:
app.use(cookieParser())
You will also need to import it:
const cookieParser = require('cookie-parser')
...or just remove it completely if you don't need it.
I hope this helps.

Error: Request failed with status code 404 (Node.js + Vue.js)?

I am little bit confused and need some help.
I write an HTTP server using Node.js, and make an HTTP request from Vue.js to the HTTP server. Somehow it always return error like this:
Error: Request failed with status code 404
at FtD3.t.exports (createError.js:16)
at t.exports (settle.js:18)
at XMLHttpRequest.f.(:3010/anonymous function) (http://localhost:3010/static/js/vendor.1dc24385e2ad03071ff8.js:1312:88758)
It seems like url address don't correct cause error is 404 in browser. I check url address several times but did't notice something wrong. What I miss?
P.S. The main task to load file from remote sftp server from website. I use to that task ssh2-sftp-client library as backend side.
When user click the button, application run getFile function where we send post request to HTTP server.
Code inside Vue.js component:
getFile (fileName) {
axios.post('http://localhost:3010/csv', {file_name: fileName}, {headers: {'Authorization': this.token}}).then(response => {
console.log(response)
this.showAlert('You download file successfully.', 'is-success', 'is-top')
}).catch((error) => {
console.log(error)
this.showAlert(error, 'is-danger', 'is-bottom')
})
}
app.js:
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
const csvRouter = require('./server/routes/csv')
const app = express();
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/csv', csvRouter);
module.exports = app;
routers/csv.js:
const express = require('express')
const router = express.Router()
const csvControllers = require('../controllers/csv')
router.get('/', csvControllers.getFile)
module.exports = router
controllers/csv.js:
const request = require('request')
const queryString = require('query-string')
let Client = require('ssh2-sftp-client')
let sftp = new Client()
const config = require('../config')
exports.getFile = (req, res) => {
console.log(req) // In console I don't notice nothing.
let data = {
file_name: req.query.file_name
}
let options = {
method: 'port',
json: true,
header: {'Authorization': req.header.token},
url: `http://localhost:3010/csv?` + queryString.stringify(data)
}
request(options, (error, response) => {
console.log('Message') // In console I don't notice nothing.
if (response) {
sftp.connect(config.sftpServer).then(() => {
return sftp.get('/reports/' + data.file_name)
}).then((chunk) => {
console.log(chunk)
}).catch((err) => {
console.log(err)
})
} else {
response.status(500).send(error)
}
})
}
It seems that app.listen(port) is missing in your app.js file:
app.listen(3000)
https://expressjs.com/en/starter/hello-world.html
In controllers/csv.js you never send a response. You should have a res.send or res.render or res.json somewhere.

Categories

Resources