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();
});
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'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.
I tried using this code but page just keep loading and nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res, next) => {
request(surl, (error, response, body) => {
// res.setHeader("Content-Type", "application/json; charset=utf-8");
res.json(body)
console.log('body:', body);
console.log('body:', req.body);
});
});
app.listen(3000, () => { console.log('On port 3000...') });
And if I comment out these two lines in my code below
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
It gives this kind of output.
"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"
If anyone could give me a start that would be great! Thanks.
The output is gibberish because body is gzip compressed. It's not JSON, not even text:
To return it to browser, the easiest way is using pipe:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request(surl).pipe(res);
});
Or, if you want to manipulate/change the body, gzip: true option can be used:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request({
url: surl,
gzip: true
}, function(error, response, body) {
let bodyObj = JSON.parse(body);
// change bodyObj...
res.json(bodyObj);
});
});
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 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.
I am trying to use the Cors middleware but it is not working
I followed the simple instructions in the documentation, but I am still getting this dreaded error.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
Can anyone help me? This is the index.js file of my backend API, where I try to implement the middleware.
const express = require('express');
const passport = require('passport');
const http = require('http');
const morgan = require('morgan');
const LocalStrategy = require('passport-local').Strategy;
let path = require('path');
let mongoose = require('mongoose');
let config = require('./config/config');
let bodyParser = require('body-parser');
let recipeRouter = require('./routes/recipeRouter');
let userRouter = require('./routes/userRouter');
/// Here, I required the middleware.
let cors = require('cors');
const app = express();
// set up DB
mongoose.connect(config.mongoUrl);
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
// Set up App
app.use(morgan('combined'));
/*
This is another attempt to get this to work. Tried it, but didn't work.
app.use(function(req, res, next){
const origin = req.get('origin');
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
/// res.header('Access-Control-Allow-Methods', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma, x-auth');
});
*/
/// Here I try to apply the middleware.
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' }));
// !! NEW !! //
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', userRouter);
app.use('/recipes',recipeRouter);
// Set up Server
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
Can anyone help? Am I missing something?