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);
});
Related
On the client side, I have an application based on threejs an d javascript. I want to send data to the server written in express using fetch. Unfortunately, the server does not receive the data and the browser also gives an error:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Application:
this.username = prompt("Username:");
const body = JSON.stringify({ username: this.username });
fetch("http://localhost:3000/addUser", { method: "POST", body })
.then((response) => response.json())
.then(
(data) => (
console.log(data), (this.aktualny_album_piosenki = data.files)
)
);
Server:
var express = require("express")
var app = express()
const PORT = 3000;
var path = require("path");
app.use(express.static('dist'));
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.post("/addUser", function (req, res) {
console.log(req.body)
})
I might be wrong but maybe try... (very bottom of your main server file)
app.listen((PORT) => {
console.log(`app is listening on port ${PORT}`);
})
is required maybe? I have this chunk of code in every project of my own so maybe that could fix the server not recognizing the api request
express documentation on app listen
heres what I use typically... this is a boilerplate for every one of my projects
const express = require("express");
const app = express();
const connectDB = require("./config/db.js");
const router = express.Router();
const config = require("config");
// init middleware
const bodyParser = require('body-parser');
const cors = require("cors");
const mongoDB = require("./config/db.js");
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const xss = require('xss-clean');
const helmet = require("helmet");
const mongoSanitize = require('express-mongo-sanitize');
const rateLimit = require("express-rate-limit");
const PORT = process.env.PORT || 5000;
mongoDB();
app.options('*', cors());
app.use('*', cors());
app.use(cors());
const limitSize = (fn) => {
return (req, res, next) => {
if (req.path === '/upload/profile/pic/video') {
fn(req, res, next);
} else {
next();
}
}
}
const limiter = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000 * 1000, // remove the last 1000 for production
message: 'Too many requests' // message to send
});
app.use(xss());
app.use(helmet());
app.use(mongoSanitize());
app.use(limiter);
// app.use routes go here... e.g. app.use("/login", require("./routes/file.js");
app.get('*', function(req, res) {
res.sendFile(__dirname, './client/public/index.html')
})
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.get('/*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
if (process.env.NODE_ENV === "production") {
// Express will serve up production files
app.use(express.static("client/build"));
// serve up index.html file if it doenst recognize the route
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
}
})
app.get('/*', cors(), function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
};
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}!`);
});
client-side fetch request looks good to me its prob a server/express.JS thing but like i said i may be wrong but worth trying
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 can't figure out how to query the MySQL database from the promise in my route file. I'm writing a RESTful API to query a MySQL database with GET methods. I'm using Express and Axios for Javascript promises.
I want to get back the list of books from a SQL table and the count of how many listings in the returned JSON.
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const bookRoutes = require('./api/routes/books');
const entryRoutes = require('./api/routes/entries');
const connection = mysql.createConnection({
host: 'localhost',
user: 'rlreader',
password: process.env.MYSQL_DB_PW,
database: 'books'
});
app.use(morgan('dev'));
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', 'GET');
return res.status(200).json({});
}
next();
});
// Routes which should handle requests
app.use('/books', bookRoutes);
app.use('/entries', entryRoutes);
app.use((req, res, next) => { //request, response, next
const error = new Error('Not found');
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
module.exports = app;
books.js
const express = require('express');
const router = express.Router();
const axios = require('axios');
//do I import something for mysql here?
router.get('/', (req, res, next) => {
axios.get('/').then(docs => {
res.status(200).json({
"hello": "hi" //want to query MySQL database here
})
}).catch(err => {
res.status(500).json({
error: err
});
})
});
module.exports = router;
Any help would be appreciated. For starters, how do I get const connection from app.js to books.js?
I moved the code connecting to the MySQL database to a separate file and included that:
const con = require('../../db');
Next, I had to properly return the response:
router.get('/', (req, res, next) => {
let responseData = axios.get('/').then(docs => {
const sql = "SELECT title, id FROM books";
con.query(sql, function (err, result) {
if (err) {
console.log("error happened");
}
return res.status(200).json(result);
});
}).catch(err => {
res.status(500).json({
error: err
});
});
});
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 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.