Sending data from Javascript to Node.js - javascript

I am trying to create a very basic function,
suppose my javascript data is
const data = 1234;
how do i send this data to a node server i created using express framework
const express = require("express");
const app = new express();
app.get("/", (req, res) => {
res.send("home");
});
app.post("/datastream", function (req, res) {
res.send('You sent the data: "' + req.body.data + '".');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`server started on port ${PORT}`));

If you want to send it from browser and your server is running locally:
const data = 1234
fetch('http://localhost:5000/datastream', {
method: 'POST',
body: JSON.stringify({ data }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.text())
.then(data => console.log(data))
.catch(err => console.log(err))
Now you need to install body-parser middleware to be able to deserialize your JSON data npm install body-parser and attach it to your app. Add this to your server code:
const bodyParser = require('body-parser')
// ...
app.use(bodyParser.json())
If everything went good (your server is running on specified port) then it should log You sent the data: 1234. after you run your browser code

You can send data from client to server using fetch method (very basic example):
const data = 1234;
fetch('/datastream', {
method:"POST",
body: JSON.stringify({data: data})
}).then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch(function(err) {
console.log('Fetch Error :' + err);
});

Related

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

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/"

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 })

HPM Error occurred while trying to proxy request (using react + express)

[HPM] Error occurred while trying to proxy request /api/users/ from localhost:3000 to http://localhost:5000 (ECONNRESET)
I get this error while trying to do axios.post request,
i'm running my app with concurrently (server with express and client side using react) ,
as described here I defined client/src/setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
my server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
//connect Database
connectDB();
//Init MiddleWare -allows to get the data from req.body
app.use(express.json());
//Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/posts", require("./routes/api/posts"));
app.get('/', (req, res) => res.send('API is running'));
//Port - first look for an environment port (when connect to heroku)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`server listening on port: ${PORT}`);
})
and my post request in the client side:
export const register = ({ name, email, password}) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const body = JSON.stringify({name, email, password});
try {
const res = await axios.post('/api/users/', body, config);
console.log({res});
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
console.log('passed dispatch')
} catch (e) {
const errors = e.response.data.errors;
if(errors) {
errors.forEach(e => dispatch(setAlert(e.msg, 'danger')));
}
dispatch({
type: REGISTER_FAIL
})
}
}
any idea what I miss ?
EDIT:
I've noticed that my server using type ipv6 and client on ipv4, maybe that's the problem ? how I make them run on the same ipv ?

Get POST request body with express and fetch

I'm new to server-side development.
I'm trying to set up a node.js server that can receive posts.
My client-server code sends the post request:
function post(){
fetch('/clicked', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Text'})
})
.then(function(response){
if(response.ok){
console.log('POST success.');
return;
}
throw new Error('POST failed.');
})
.catch(function(error){
console.log(error);
});
}
And my Node.js server receives it:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
})
However, my server console logs all undefined.
What should I do to receive my POST request body?
Try setting up express.json() inside the app:
const express = require('express');
const app = express();
app.use(express.json())
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
});
Add this before handling post request.
app.use(require('body-parser').json());
What body-parser does is, it will add all the information we pass to the API to the 'request.body' object.

req.body is empty whith fetch request

i'm trying to make a fetch request to my server.
but i keep getting an empty req.body.
client script:
const form = document.getElementById('form1')
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
const link = formData.get('link');
var payload = {
link
};
console.log(payload);
const options = {
method: "POST",
body: JSON.stringify(payload),
headers: {
'content-type': 'application/json'
}
}
console.log(options);
fetch('/api/gtmetriks', options)
.then(response => response.json()).then(result => console.log(result)).catch(err => console.log(err));
})
server code:
const bodyParser = require('body-parser');
const cors = require('cors')
const app = express()
//cors
app.use(cors())
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json())
app.post('/api/gtmetriks', (req, res) => {
console.log(req.body);
})
so when i post the request i get in the console '{}'.
but no errors in the clients browser.
I think the problem is that you are using CORS but not specifying which URL to POST to. For example, your client is http://localhost:3000 but your server is http://localhost:3001. You are sending the fetch to http://localhost:3000/api/gtmetriks instead of http://localhost:3001/api/gtmetriks.
If you change your fetch to:
fetch('[YOUR SERVER URL]/api/gtmetriks', options)
.then(response => response.json())
.then(result => console.log(result))
.catch(err => console.log(err));
})
It should work.
EDIT #1:
This code worked for me using a React frontend (3000) and an Express backend (3001):
Client app.js
import React, { Component } from 'react';
export default class App extends Component {
handleSubmit = () => {
const payload = {
link: 'http://tesla.com',
};
const options = {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'content-type': 'application/json',
},
};
fetch('http://localhost:3001/api/gtmetriks', options)
.then(response => response.json())
.then(result => console.log(result))
.catch(err => console.log(err));
};
render() {
return (
<button
onClick={() => {
this.handleSubmit();
}}>
Click Me
</button>
);
}
}
Server server.js
const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const app = express();
//use cors to allow cross-origin resource sharing
app.use(
cors()
);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post('/api/gtmetriks', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
//start your server on port 3001
app.listen(3001, () => {
console.log('Server Listening on port 3001');
});

Categories

Resources