I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.
This is my complete code.
This is my react file 'member.js', run on port 3000 (http://localhost:3000/member).
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Member extends Component {
constructor() {
super();
this.state = { player: {} };
}
handleSubmit(e) {
e.preventDefault();
fetch('http://localhost:4000/player', {
mode: 'no-cors',
method: 'post',
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify({
number: 123,
name: "John",
position: "Andrew"
})
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
}
render() {
return (
<div className="member-page">
<form>
<input type="submit" onClick={this.handleSubmit.bind(this)} />
</form>
</div>
)
}
}
export default Member;
and this is my node file 'player.js', run on port 4000 (http://localhost:4000/player).
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
I don't know where I do a mistake, please anyone correct my code either member.js or player.js.
Thank you very much for all the help.
I agree with #robertklep. I think problem is in var player = req.body;
Try:
Install body-parser npm package
npm i -S body-parser
Configure body-parser
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//enable CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', (req, res) => {
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => {
if (error) throw error;
// Neat!
});
res.send('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
var router = express.Router();
router.use( bodyParser.json() ); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(5000, () => {
console.log('Example app listening on port 5000!')
})
app.use('/', router);
Try to Configure your node server like this
First install body-parser using :
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
If you are passing string data then use
app.use(bodyParser.text());
Otherwise if you are passing data as Json then use
app.use(bodyParser.Json());
It should work in your case.
Related
Whenever I try to run node index.js, I am getting "Error [MongooseError]: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string"
Also, index.js and .env are in the same directory.
index.js:
const express = require('express');
require('dotenv').config();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
mongoose.connect(process.env.DB, { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));
mongoose.Promise = global.Promise;
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.use(bodyParser.json());
app.use('/api', routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.listen(port, () => {
console.log(`Server running on port ${port}`)
});
.env:
NODE_ENV = development
PORT = 3000
MONGO_URI = mongodb+srv://"User":1#cluster0.da5tj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
You are having just a little error here but here is the fix, your .env stores your connection string as MONGO_URI and your main code is calling process.env.DB which causes the mongoose error you are getting, i have run your code with my db and its working fine your code should be like below without changing your .env file
const express = require('express');
require('dotenv').config();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
.then(() => console.log(`Database connected successfully`))
.catch(err => console.log(err));
mongoose.Promise = global.Promise;
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.use(bodyParser.json());
app.use('/api', routes);
app.use((err, req, res, next) => {
console.log(err);
next();
});
app.listen(port, () => {
console.log(`Server running on port ${port}`)
});
I was having same issue and this worked for me. Require in dotenv.
require('dotenv').config()
...and setting the .env file with variable MONGO_URI = my database connection
...and finally making sure to pass the following into mongoose.connect:
process.env.MONGO_URI
Hope that helps. I am noob, so don't count on me being able to answer many questions.
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 new to Node and I can't seem to get my request to complete. I'm just trying to create a basic handshake between server and client by sending the location for the client to the server and displaying that into the server log. I'm not sure why I can't display the data into the log.
Index.js
const express = require('express');
const app = express();
app.listen(8080, () => console.log('listening at 8080'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
app.post('/api',(request,response) => {
console.log('I got a request!');
console.log(request.body);
});
Index.html
<script>
if('geolocation' in navigator) {
console.log('geolocation is avaliable');
navigator.geolocation.getCurrentPosition(async position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(lat,lon);
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lon;
const data = {lat, lon};
const options = {
method: 'POST',
header:{
'Content-Type':'application/json'
},
body: JSON.stringify(data)
};
fetch('/api',options);
});
} else{
console.log('geolocation is not avaliable');
}
</script>
Some things to note. The request does seem to complete and no errors are shown in the developer console.
Server information:
-[nodemon] restarting due to changes...
-[nodemon] starting node index.js
-listening at 8080
-I got a request!
-{}
Add the following to your index.js:
npm i -S body-parser
// Takes the raw requests and turns them into usable properties on req.body
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/api', (request, response) => {
console.log('I got a request!');
console.log(JSON.stringify(request.body));
});
Try the following code in your index.js
const express = require('express')
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
}
next();
});
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 am having a strange issue with cookies in my node app. It is hosted on Heroku and I use JSON Web Tokens stored in a cookie that is authenticated by my express middleware. When I login on my Macbook pro, the cookie is successfully stored. However, when I use Linux Mint desktop, or an Android tablet, the site logs in but then redirects on protected routes and the cookie is never set.
This is where the cookie is set on login:
let token = jwt.sign({
username: user.username,
email: user.email
}, config.privateKey, {
expiresIn: '7d'
});
let userResponse = {
success: true,
message: 'Successfully logged in!',
id: user._id,
email: user.email,
username: user.username
}
// set cookie for 7 days
res.cookie('auth_token',
token,
{maxAge: 604800000, path: "/"}).json(userResponse);
Here is my server.js file:
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const env = process.env.NODE_ENV || "development";
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const config = require('./app/config/config.js');
process.env.PWD = process.cwd();
// Establish connection with MongoDB
mongoose.connect(config.db.connectString);
app.use(cookieParser());
// Allowing X-domain request
var allowCrossDomain = 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, Cache-Control");
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('public'));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', () => {
console.log('Connected to sondage database');
});
// ===== Import Routers ======
const userRouter = require('./app/routes/user.routes')(express, app);
const pollRouter = require('./app/routes/poll.routes')(express, app);
const authRouter = require('./app/routes/auth.routes')(express, app);
app.use('/api/users', userRouter);
app.use('/api/polls', pollRouter);
app.use('/api/', authRouter);
// For all other requests, use React Router
app.get('*', function (request, response){
response.sendFile(process.env.PWD + '/public/index.html');
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server running');
});
EDIT I have traced this down to a http vs https issue. If I use https in the request, the cookies work. Otherwise cookies aren't set. So I need a way to force the user to do HTTPS.
I was able to fix this using the heroku-ssl-redirect node package. This takes requests and forces the browser to use https for each request.