Sending data formData througt Javascript to Express API - javascript

So, when i handle a post request througt javascript, i send the data to the api, and i don't know how to log the data in the API.
What i tried
app.post("/register", (req,res) => {
res.render("register/register", {});
-> i tried to log it as req.query, req.params or req.body console.log(req.query)
})
JS code:
document.querySelector("#regForm").addEventListener('submit', e => {
e.preventDefault();
let username = document.querySelector("#username").value;
let formData = new FormData(document.querySelector("#regForm"));
console.log([...formData]);
let data = JSON.stringify([...formData]);
console.log(data)
const request = new XMLHttpRequest();
request.open("POST", '/register');
request.send(data);
})
Edit:
The full API code:
const express = require("express");
const path = require("path");
var bodyParser = require('body-parser')
const app = express();
const port = process.env.POST || "8080";
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.listen(port, () => {
console.log(`Running on port ${port}`);
})
// middleware & static files
app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/src'));
app.get("/profile/:name", (req,res) => {
res.render("profile", {username:req.params.name});
})
app.get("/register", (req,res) => {
res.render("register/register", {});
})
app.post("/register", jsonParser, (req,res) => {
res.render("register/register", {});
console.log(req.body)
})
Answer to LakiMancic - The error:
error
And nothing works. Can you help me? Thanks!

Try to specify Content-Type of your XMLHttpRequest with
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
After request.open(...); and before request.send(...);
Update ( Full Code that worked for me ):
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/main.html');
});
app.post("/register", (req,res) => {
console.log(req.body)
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
document.querySelector("#regForm").addEventListener('submit', e => {
e.preventDefault();
let username = document.querySelector("#username").value;
let formData = new FormData(document.querySelector("#regForm"));
console.log([...formData]);
let data = JSON.stringify([...formData]);
console.log(data)
const request = new XMLHttpRequest();
request.open("POST", '/register');
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(data);
})

Related

access localhost with smartphone and get no response from the server

website works via localhost on pc
access with smartphone to localhost via ip too (I receive html, css and js for client)
when I click the button, a "hi" is also added but function "search()" is not executed
but when I enter the url http://localhost:3000/users I get the "hi1"
What do i have to do to make this work?
Client Side
const button = document.querySelector("button");
button.addEventListener("click", () => {
document.getElementById("imageDiv").innerHTML = "Hi";//this work
search();//this not work
});
async function search(){
await fetch("http://localhost:3000/users")
.then(response => response.json())
.then(response => {
var image;
image = JSON.parse(JSON.stringify(Object.assign({},response)));
document.getElementById("imageDiv").innerHTML = response;
})};
Server Side
const express = require('express');
const bodyParser = require('body-parser');
const path = require("path"); // window or mac
const cors = require('cors');
const app = express();
const port = 3000;
//var word = "";
//const router = express.Router();
// configure CORS to avoid CORS errors
app.use(cors());
// configure body parser so we can read req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('./client'));
app.get('/', (req, res) => {
res.sendFile("./index.html");
});
app.get("/users", (req, res) => {
datafiles = ["hi1"];
res.json(datafiles);
res.status(200);
});
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});

Upload image and read json with express js

Problem:
Trying to get json string but req.body in the post data handler returns undefined. Is it even possible to send json and file in one post request to the server?
Code:
Data sended to the server:
function saveFile(e) {
let info = {titleI: title.value, dirI: dir.value};
let xhr = new XMLHttpRequest();
let formData = new FormData();
let file = e;
formData.append("info", JSON.stringify(info));
formData.append("file", file);
xhr.onreadystatechange = state => { console.log(xhr.status); }
xhr.timeout = 5000;
xhr.open("POST", '/register');
xhr.send(formData);
}
The post data handler:
router.post("/", (req, res) => {
console.log(req.body.info)
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
let dirName = "a"
fs.mkdir("D:/node website/ipgrabber/files/"+dirName+"/", function(err) {
if (err) {
console.log(err)
}
})
fstream = fs.createWriteStream("D:/node website/ipgrabber/files/"+dirName+"/" + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
})
This is the main class:
var express = require('express')
var http = require('http')
const mongoose = require('mongoose')
const { json } = require('express')
var cookieParser = require('cookie-parser')
var app = express()
var server = http.createServer(app)
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));
var busboy = require('connect-busboy');
app.use(busboy());
//error handler
mongoose.connect('mongodb://localhost:27017/grabber', {useNewUrlParser: true, useUnifiedTopology: true});
app.use(cookieParser())
app.set("view engine", "ejs")
app.set('views', __dirname+'/views/html/');
app.use("/js", express.static(__dirname + "/views/js"))
app.use("/css", express.static(__dirname + "/views/css"))
const registerRoute = require("./routes/register")
const grabberRoute = require("./routes/grabber")
app.use("/register", registerRoute)
app.use("/id", grabberRoute)
app.get("/", (req, res) => {
res.redirect("/register")
})
app.use(function (err, req, res, next) {
res.status(400).send("Error code: 2 <hr> This page is currently inaccessible! <br> <a href='/'>GO TO HOMEPAGE</a>")
console.log(err)
})
server.listen(80)
Project resources:
body-parser - 1.19.0
connect-busboy - 0.0.2
cookie-parser - 1.4.5
crypto-js 4.0.0
ejs 3.1.5
express 4.17.1
mongoose 5.11.19
By default, express can't manage to get multipart/form-data correctly.
You have to use a middleware to handle and parse this request.
I recommend to use multer.
In your case, you're using connect-busboy so the info should be handled like this:
req.busboy.on('field', function(key, value, keyTruncated, valueTruncated) {
console.log('your info is here', key, value);
});

unable to send post request using socket.io

here i am sending data from socket client to socket server and after receiving the request it has to send to node api
**the issue is im getting null ** on calling the socket server
below is my code
Socket Client
socket.connect();
socket.emit("posreq",JSON.stringify({ "title": "data"}));
Socket Server
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
request = require('request'),
cors = require('cors'),
server = http.createServer(function (req, res) {
// your normal server code
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end('Hello world');
});
server.listen(4000);
// socket.io
var socket = io.listen(server);
socket.on('connection', function (client) {
// new client is here!
client.on('posreq', function (postdata) {
request.post("http://localhost:3000/book", {
body: postdata
}, function (res) {
console.log(res);
client.send("post req called",postdata);
});
});
client.on('disconnect', function () {
console.log('connection closed');
});
});
Node api
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express()
const port = 3000
let books = [{
"title": "Eloquent JavaScript, Second Edition",
}];
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/book', (req, res) => {
const book = req.body;
// output the book to the console for debugging
console.log(book);
// books.push(book);
res.json('Book is added to the database');
});
I tried but unable to understand the issue
Note : How can i convert the Socket server to express js code
As far I understand you are willing to use express instead of HTTP and that will solve your problem. And in the below code, I have used express as well as HTTP. Try code below
const express=require("express")
const app=express()
const server=require("http").createServer(app)
const socket=require("socket.io")(server)
server.listen(4000,()=>console.log(`Listening to port 4000`))
socket.on('connection', function (client) {
client.on('posreq', function (postdata) {
request.post("http://localhost:3000/book", {
body: postdata
}, function (res) {
console.log(res);
client.send("post req called",postdata);
});
});
client.on('disconnect', function () {
console.log('connection closed');
});
});
May be you need few modification,
Request is depricated so better to use axios or other alternative.
const express = require("express")
const bodyParser = require("body-parser")
const axios = require('axios')
const app = express()
const httpServer = require("http").createServer(app)
const socket = require("socket.io")(server)
app.use(bodyParser.json({ limit: '16mb' }));
app.use(bodyParser.urlencoded({ limit: '16mb', extended: true, parameterLimit: 50000 }));
app.get('/', (req,res)=> res.send("Hello world"));
socket.on('connection', function (socket) {
socket.on('posreq', async (body) => {
try {
const { data } = await axios.post("http://localhost:3000/book", { body })
socket.send("post req called", data);
} catch (error) {
socket.send("post req error", error);
}
});
socket.on('disconnect', function () {
console.log('connection closed');
});
});
httpServer.listen(3000, () => console.log(`Spinning 3000`))

cannot GET / when serving Angular app using express and nodejs

I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html

Saving data to json using nodejs and cointicker

Im learning nodejs and I'm creating a server to get the price of cryptocurrencies using a npm called Coin-Ticker. I want to use the data I'm getting in an Angular app but it's not displaying the data in the html. This is my code:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
Thanks for your help!
It is because coin ticker returns the json in the then so when you are doing res.status(200).json(posts.data); it is returning undefined. just replace that with res.status(200).json(posts) and it should work
Also you can not do router.get((req, res) => {
you need a path before this. I tried this code with
router.get('/convert', (req, res) => { and with the changes above it worked

Categories