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));
Related
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 am trying to pass the generalDetail data from my react front end to my node server. I am currently getting a connection refused error.
(OPTIONS http://localhost:5000/api/home net::ERR_CONNECTION_REFUSED).
here is my onSubmitForm function:
onSubmitForm(e){
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/home", data).then(() => {
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
}
//end
onContentChange(fieldname, data){
console.log('On Content Change', data);
this.setState({
[fieldname]: data
});
}
}
Here is my server.js file
const express = require('express');
const app = express();
// http://localhost:5000/api/home
app.post('/api/home', (req, res) => {
const data = [
{req.body.generalDetail},
];
res.json(data);
});
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);
You can change your code into this
Example
onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/api/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
}
try this
const express = require('express')
const app = express()
const port = 8000 //your port number
const cors = require('cors')
app.use(cors())
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
Try to add cors preflight code in your backend code (server.js).
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.post('/api/home', (req, res) => {
const data = [{ generalDetails: req.body.generalDetail }];
res.json(data);
});
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 am not exactly sure how to go about using/accessing the data requested from a discord oauth2 authentication. I have requested to access the guilds the user is in and the username and avatar of the user. I get a successful authentication, but my question is how do i use and access that data? This is my code currently:
server.js
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'index.html'));
});
app.listen(50451, () => {
console.info('Running on port 50451');
});
app.use('/api/discord', require('./api/discord'));
app.use((err, req, res, next) => {
switch (err.message) {
case 'NoCodeProvided':
return res.status(400).send({
status: 'ERROR',
error: err.message,
});
default:
return res.status(500).send({
status: 'ERROR',
error: err.message,
});
}
});
discord.js
const express = require('express');
const dotenv = require('dotenv').config()
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const router = express.Router();
const scopes = ['identify', 'guilds'];
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect =
encodeURIComponent('http://localhost:50451/api/discord/callback');
router.get('/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`);
});
router.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
res.redirect(`/success/?token=${json.access_token}`);
}));
module.exports = router;
Any help will be greatly appreciated. Thanks!
It's almost the same as the way you use the req.query.code to get the access_token.
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
yourUserId = `${userInfo.id}`;
yourUserName = `${userInfo.username}`;
// or simply...
console.log(userInfo);
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)
};