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)
};
Related
I'm creating a virtual store as part of my Bootcamp projects and ran into this problem when trying to get the confirmation page from the cart page using the fetch post method I get a 404 error. Not sure if it's a server issue or my code.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"firstName": "kk",
"lastName": "41k421k",
"address": "14125415",
"city": "541521",
"email": "515k215",
"products": [
"107fb5b75607497b96722bda5b504926"
]
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost:3000/api/order", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
// product.js (routes)
const express = require('express');
const router = express.Router();
const productCtrl = require('../controllers/product');
router.get('/', productCtrl.getAllProducts);
router.get('/:id', productCtrl.getOneProduct);
router.post('/order', productCtrl.orderProducts);
module.exports = router;
// app.js
const express = require('express');
const path = require('path');
const productRoutes = require('./routes/product');
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(express.static('images'));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use('/api/products', productRoutes);
module.exports = app;
// product.js (controller)
exports.orderProducts = (req, res, next) => {
if (!req.body.contact ||
!req.body.contact.firstName ||
!req.body.contact.lastName ||
!req.body.contact.address ||
!req.body.contact.city ||
!req.body.contact.email ||
!req.body.products) {
return res.status(400).send(new Error('Bad request!'));
}
let queries = [];
for (let productId of req.body.products) {
const queryPromise = new Promise((resolve, reject) => {
Product.findById(productId).then(
(product) => {
if (!product) {
reject('Product not found: ' + productId);
}
product.imageUrl = req.protocol + '://' + req.get('host') + '/images/' + product.imageUrl;
resolve(product);
}
).catch(
() => {
reject('Database error!');
}
)
});
queries.push(queryPromise);
}
The request URL and the URLs in the server code don't match.
The request is sent to http://localhost:3000/api/order but the server is listening for the post request at http://localhost:3000/api/products/order.
Change the fetch request to
fetch("http://localhost:3000/api/products/order", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I am trying to make a post request from my react app to the express server. On making the post request from postman works fine but when I make it from my react app It gives error 500 (Internal server error)
This is my client side code-
function signUpWithEmail(e,email,password,ConfirmPassword,userHandle) {
e.preventDefault();
let params = {
email: email,
password: password,
ConfirmPassword: ConfirmPassword,
userHandle: userHandle
}
let res = axios({
method: 'post',
url: 'http://localhost:3031/signUp/',
data : params,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
},
validateStatus: (status) => {
return true
},
})
.then(() => console.log('Created'))
.catch((err) => {
console.log(err.message)
})
This is my server code
`const functions = require('firebase-functions');
const express = require('express')
const app = express()
const port = 3031;
const cors = require('cors');
const { signup } = require('./server/users');
const { login, getAuthenticatedUser } = require('./server/users');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000/");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors())
app.use(bodyParser.json())
app.get('/', (req, res) => res.send('Hello World!'))
app.post('/signUp',cors(),signup);
app.post('/login', login);
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');
});
I make put request, but my request.body is empty object
main.js
company = await fetch(`http://localhost:8080/companies/${company.id}`, {
method: "PUT",
body: JSON.stringify({ name: "my company" }),
headers: { 'Content-Type': 'application/json'} })
.then(res => res.json()).then(data => data);
company.route.js
this.__router.put('/:id', (req, res) => {
const { body, params: { id } } = req;
console.log(body);
companyController.updateOne(id, body);
res.status(200).end();
});
company.controller.js
updateOne(id, {name}) {
const company = this.findOne(id);
company.name = name || company.name;
return company;
}
app.js
app.use(bodyParser.json());
app.use('/*' , function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.urlencoded())
app.use(bodyParser.urlencoded({
extended: true
}));
What could be the problem?
My issue is similar to this one, all answers there didnt help me.
I'm using Passport.js with local strategy (passport-local-mongoose).
The middleware below works on Postman but fails whenever I try from my React client.
exports.isLoggedIn = (req, res, next) => {
console.log(req.user) // undefined with react, but works from postman
if (req.isAuthenticated()) {
return next();
}
}
Here's my app.js:
require('./handlers/passport');
app.use(cors())
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: true,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
handlers/passport.js:
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
user.js (model):
...
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });
CLIENT CODE:
const url = 'http://localhost:7777/users/<id>';
const config = {
headers: {
'Content-Type': 'application/json',
},
};
axios.put(url, data, config)
.then(res => console.log(res))
.catch(err => console.log(err));
Am I missing something? does passportLocal strategy means that I can't use with an API and a client like my example? Thanks :D
So, after some time I could find an answer:
Server sends SetCookie header then the browser handle to store it, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.
I had to set withCredentials: true in my client. (axios.js)
const config = {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
};
axios.put(url, { page: '123' }, config)
.then(res => console.log('axios', res))
.catch(err => console.log('axios', err));
Then I had CORS problems.
So I added this to my express server:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});