req.body is empty whith fetch request - javascript

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

Related

I am trying to make routes but somehow express routers are not working

I think that I am not making any mistake in the code. I am not getting why this is not working when I am trying to access it on localhost. working fine on postman. should I change something in the browser setting
server.js (starting point- calling all the methods here)
const express = require('express')
const app = express();
const controller = require('./mailtemplate/mailtemplate.controller')
var http = require("http")
app.use('/mailtemplate', controller);
app.get('/', (req,res) => {
res.send("Server is Live")
})
var server = http.createServer(app);
server.listen("3000", "here is my IP address", () => {
console.log("Server is running")
});
controller.js - setting routs here
const express = require('express');
const router = express.Router();
const app = express();
const mailtemplateService = require('./mailtemplate.service');
router.post('/template', getMail);
app.use(router)
function getMail(req, res, next) {
mailtemplateService.getDataFromOpenAIAPI(req.body)
.then((response) => {
console.log(response);
res.json();
})
.catch(err => next(err))
}
module.exports = router;
service.js - logic of the fetching data from the api
const express = require('express')
const db = require('../_helpers/db');
const MailTemplate = db.MailTemplate;
async function getDataFromOpenAIAPI(prompt) {
const apiKey = "apikey";
const endpoint = "https://api.openai.com/v1/completions";
try{
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "text-davinci-003",
prompt:prompt,
max_tokens : 600,
temperature:0.6
})
})
const data = await response.json();
console.log(data.choices[0].text);
return data;
}catch (error){
console.log(error);
}
}
module.exports = {getDataFromOpenAIAPI};

Next js/react Unable to set a cookie

so i am trying to get a cookie in next js and using express but the backend works fine with postman and get the cookie token but the problem is the frontend is not getting the cookie and here is my backend:
const express = require("express");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(cookieParser());
app.post("/", (req, res) => {
res.cookie("token", req.body.token).send({ msg: "DONE" });
});
app.listen(5000, () => {
console.log("running on http://localhost:5000");
});
and here is the frontend:
import styles from "../styles/Home.module.css";
export default function Home({ cookies }) {
return (
<div className={styles.container}>
<h1>Cookies: {cookies}</h1>
<button
onClick={() => {
fetch(`http://localhost:5000/`, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ token: "ACBD" }),
});
}}
>
Genrate Cookies
</button>
</div>
);
}
it is returning:
Unhandled Runtime Error
TypeError: Failed to fetch
is there a mistake here also i have tried to put this in a getServerSideProps() but it still does not work.
I use js-cookie. it works great
get and set Cookies in React.useEffect in the frontend

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 ?

Sending data from Javascript to Node.js

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

Post Form Request Object Is 'object Object'

Just getting into Node & I have read a few questions here on SO regarding this, however, the request body continues to be { 'object Object' : ''}
The server code is :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.get('/', (req, res) => {
res.send('this is a normal response');
});
app.post('/d*', (req, res) => {
const reqBody = req.body;
console.log(req.body); // console => {`object Object` : ''}
res.send(reqBody);
});
app.listen(app.get('port'), () => console.log('Server instance running on http://localhost:1111'));
The client side function is a simple 'fetch request':
const postRegistrationForm = (userDetails, dispatch) => {
const url = 'http://localhost:1111/d/register';
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: userDetails
};
fetch(url, config)
.then(data => data.json())
.then(res => console.log('rezzz is...', res));
};
You need to stringify any body/object before sending it with fetch.
Try using this config for your fetch:
const config = {
method: 'POST',
headers: {
'Accept': 'application/json'
'Content-Type': 'application/json'
},
body: JSON.stringify(userDetails)
};

Categories

Resources