I have the following reactjs code and using expressjs to handle the post request. req.body always returns {} from the app. But it works in Postman.
my reactjs code snippet:
handleSubmit(e) {
e.preventDefault();
fetch(config.urlDev + '/notes', {
method: 'post',
body: { "email":"test" },
//headers: {'Content-Type':'x-www-form-urlencoded'}
headers: {'Content-Type':'application/json'}
})
.then((res) => res.json())
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
my expressjs code snippet:
module.exports = function (app, db) {
app.post('/notes', (req, res) => {
console.log(req.body)
console.log(req.params)
res.send(req.body)
})
}
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient
const bodyParser = require('body-parser')
const db = require('./config/db');
const app = express();
const port = 8000;
const cors = require('cors');
const path = require('path');
app.use(cors())
//app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
MongoClient.connect(db.url, {useUnifiedTopology: true}, (err, database) => {
if (err) return console.log(err)
const mydb = database.db('notes')
require('./app/routes') (app, mydb);
app.listen(port, () => {
console.log ("server on " + port)
})
})
postman
Try un-commenting the line
//app.use(bodyParser.json()) and it should work.
or alternatively if you are sending headers in the fetch request as headers: {'Content-Type':'x-www-form-urlencoded'} instead of headers: {'Content-Type':'application/json'} it should work.
Related
I am trying to get data from a udemy API. I can get it with cURL in the console but not with fetch. Please can anyone look at my code and let me know what I am doing wrong?
const fetch = require("node-fetch");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
const path = require("path");
app.use(express.static("public"));
app.use(express.static(path.resolve(__dirname, "public")));
app.get("/", (req, res) => {
res.sendFile("index.html", { root: __dirname });
});
app.get("/contact", (req, res) => {
res.sendFile("contact.html", { root: __dirname });
});
const client_id = "client_id";
const client_secret = "client_secret";
const client = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
fetch("https://www.udemy.com/api-2.0/courses/", {
headers: {
Authorization: `Basic ${client}`,
},
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch((err) => {
console.log(err);
});
I have an input that calls this submit function onSubmit:
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setfruit(item);
console.log("sent")
fetch('/api/tasks/add', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Name: item.Name,Quantity: item.Quantity, edit: item.edit }),
}).then(() => {
setItem(itemd)
getTasks();
});
};
and my route:
router.post('/add', (req, res) => {
const { Name, Price, edit } = req.body;
const newTask = new Task({ Name, Price, edit });
newTask.save()
.then(task => res.json(task))
.catch(err => res.json(500, err));
});
Heres my index.js:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const routeTasks = require('./src/routes/tasks');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(bodyParser.json());
app.use('/api/tasks', routeTasks, (req, res) => res.sendStatus(401));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + './client/build/index.html'));
});
const port = 5000;
app.listen(port);
console.log(`listening on ${port}`);
Every time I call the onSubmit function, I get a 404 error. I can't tell why.
I used this repo as a guide for creating my express server but for some reason when I switch the underlying React app it stops working.
https://github.com/jmsv/simple-mern
Per Phil's comment, my issue was that the example Repo I was going off of used a React proxy which I hadn't configured in my own app. Once I added that to the package.json file, it worked.
When i try to make a request to my server the client send two requests, the first with an empty body, and the second with the correct body
this is my server file
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const cors = require('cors');
const bodyParser = require('body-parser');
const authMiddleware = require('./app/middlewares/auth.middleware');
const db = require('./config/db');
app.use(authMiddleware);
app.use(cors({ origin: '*' }));
app.use(bodyParser.json());
db.then(res => {
require('./app/routes')(app);
});
server.listen(3210, () => {
console.log('\x1b[0m', 'Backend escutando e enviando na porta 3210');
});
this is the route file
const userController = require('../controllers/user.controller');
module.exports = app => {
app.post('/sign-up', async (req, res) => {
try {
const signUpData = await userController.signUp(req.body);
res.status(200).json(signUpData.user);
} catch (error) {
console.log(error);
res.status(400).json(error);
}
});
app.post('/sign-in', async (req, res) => {
try {
const signInData = await userController.signIn(req.body);
res.header('x-auth-token', signInData.token);
res.status(200).json(signInData);
} catch (error) {
console.log(error);
res.status(400).json(error);
}
});
};
here is my axios configuration on my react project
import axios from 'axios';
export const apiUrl = 'http://localhost:3210';
export const api = axios.create({
baseURL: apiUrl,
headers: {
common: {
'Content-Type': 'application/json'
}
}
});
the function where i do the request
export const signIn = data => {
return api
.post(`/sign-in`, data)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
};
This error only occours when the request is made via client, when i
use postman everything works fine
I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You are sending to the client an object with the form:
{
express: data
}
And when you log that on the console you see that data is an object:
{
data: [],
type: "buffer"
}
Which means that your post request inside express is returning that object.
I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You might need to config your client as to parse response as JSON.
var options = {
mimetypes: {
json: ["application/json", "application/my-custom-content-type-for-json;charset=utf-8"]
}
};
var client = new Client(options);