Request.body is empty object after put request - javascript

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?

Related

Why does Fetch post method is giving a 404 error

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

Being blocked by CORS: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

I am getting the error
Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Whenever I try to post some data to my api using the following axios command
const [login, setLogin] = useState(
localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null
);
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${login.token}`,
},
};
await axios
.post(`${Config.SERVER_ADDRESS}/api/investments`, investmentObj, config)
.then((response) => {
console.log(investmentObj);
notify(`${response.data.name} investimento cadastrado com Sucesso`);
history.push(`/app/investment/${response.data._id}`);
})
.catch((err) => {
console.log(err);
notify(err.response.data, 'danger');
});
I don't know what to do, since I am using the following middleware:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
app.use(cors());
next();
});
I think that my issue is related to the Authorization in the headers, since my other api calls are working... Hopefully any of you guys will help me with such preflight request
I just added the following code app.options('*', cors()); and now it is everything working...
Check that out on the documentation from CORS npm https://www.npmjs.com/package/cors#enabling-cors-pre-flight
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
app.use(cors({ credentials: true, origin: true }));
next();
});
app.options('*', cors());

Axios Post request from my react app to the express server giving error 500

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

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

Node + Express + Passport: req.user Undefined but works in Postman

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

Categories

Resources