I'm trying to post data in my bdd with my node express server from my react-native app but it's doesn't work, req.body is empty. (get data and display on my react-native application works by the way..)
When I do the request in my app, I got this in my server terminal :
Go to http://localhost:3000/users so you can see the data.
req.body : {}
Connected to bdd
1 record inserted, result : OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 71,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
My react-native code :
fetch('http://localhost:3000/newuser', {
method : 'POST',
mode : 'no-cors',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body : JSON.stringify({
username : 'test',
})
}) .then((response) => response.json())
.catch((error) => {
console.error(error);
});
My node server :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'react'
});
// Starting our app.
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/users', function (req, res) {
...
});
app.post('/newuser', function (req, res) {
// console.clear()
console.log("req.body : ", req.body)
let username = req.body.username;
connection.getConnection(function (err) {
if (err) throw new err;
console.log("Connected to bdd");
const sql = "INSERT INTO users(username) VALUES ('" + username + "')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, result : ", result);
res.send('POST request')
});
});
})
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
Related
I am currently learning how to use the fetch api for my front-end. I continue to get the XHR 404 POST error.
//Backend file
const express = require("express");
const app = express();
require("dotenv");
const Port = process.env.PORT || 5000;
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
const nodemailer = require("nodemailer");
const Mail = require("nodemailer/lib/mailer");
require("nodemailer-mailgun-transport");
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile("/public");
res.sendFile("/public/js/mail.js");
});
app.listen(Port, (req, res) => {
console.log(`listening on port ${Port}`);
});
app.post("/email"),
(req, res) => {
FromMailjs = req.body;
console.log(FromMailjs);
const transporter = nodemailer.createTransport({
auth: {
user: process.env.Email,
pass: process.env.Pass,
},
});
const MailOptions = {
from: req.body.Email,
to: process.env.MyEmail,
text: `${req.body.FirstName}, ${req.body.LastName}
, ${req.body.PhoneNumber}, ${req.body.Email}`,
};
transporter.sendMail(MailOptions, (error, info) => {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Email sent");
res.send("success");
}
});
};
//Frontend file
const ContactForm = document.querySelector(".contact-form");
ContactForm.addEventListener("submit", (e) => {
e.preventDefault();
let FirstName = document.getElementById("Fname");
let LastName = document.getElementById("Lname");
let PhoneNumber = document.getElementById("PhoneNumber");
let Email = document.getElementById("Email");
const FormData = {
FirstName: FirstName.value,
LastName: LastName.value,
PhoneNumber: PhoneNumber.value,
Email: Email.value,
};
const PostOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(FormData),
};
console.log(FormData);
fetch("/email", PostOptions);
});
XHRPOSThttp://localhost:5000/email
[HTTP/1.1 404 Not Found 27ms]
I have tried changing the routes hoping that it was just a routing issue and I still get the same error. I was using XHR before fetch and I got the same 404 error. My front-end is receiving the correct information but I can't get my backend to receive the information.
You have a typo. Please use:
app.post("/email", (req, res) => {
Instead of:
app.post("/email"),
(req, res) => {
Kindly request you to point out where I am going wrong.
When I make a POST Request to the URL: http://localhost:1030/apirequestlogs/add
Record is Created in the Collection. However, Only _id, createDate & updateDate Parameters are there in the record.
app.js
let express = require('express');
let path = require('path'); // Required for Routing
let mongoose = require('mongoose');
let cors = require('cors'); // Required for Sending & Receiving Data in Chunk
let bodyParser = require('body-parser'); // Required for Handling URL GET & POST Requests
let dbConfig = require('./db/dbConfig');
let createError = require('http-errors');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database BE Server Listening on Port 27017');
},
(error) => {
console.log('Error Connecting to msermsdbs Database BE Server. ' + error);
});
const app = express();
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(cors());
const apirequestlogRoute = require('./models/common/logs/apirequests/apirequestlogRoutes');
app.use('/apirequestlogs', apirequestlogRoute);
const port = process.env.port || 1030;
const server = app.listen(port, () => {
console.log('Database FE Server Listening on Port 1030');
});
app.use((request, response, next) => {
next(createError(404));
});
app.get('/', (request, response) => {
request.send('Invalid Request');
});
app.use(function(error, request, response, next){
if(!error.statusCode) error.statusCode = 500;
response.status(error.statusCode).send(error.message);
});
apirequestlogModel.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let apirequestlogSchema = new Schema({
nid: Number,
host: String,
url: String,
server: String,
haserror: Boolean,
errorcode: Number,
errordescription: String
},
{
timestamps: true
});
module.exports = mongoose.model("logapirequests", apirequestlogSchema);
apirequestlogRoutes.js
const express = require("express");
const app = express();
const apirequestlogRoute = express.Router();
let apirequestlogModel = require('./apirequestlogModel');
apirequestlogRoute.route('/getall').get((request, response) => {
apirequestlogModel.find((error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
apirequestlogRoute.route('/getbyid/:id').get((request, response) => {
apirequestlogModel.findById(request.params.id,(error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
apirequestlogRoute.route('/add').post((request, response, next) => {
apirequestlogModel.create(request.body,(error, data) => {
if(error){
return next(error);
} else {
response.json(data);
};
});
});
module.exports = apirequestlogRoute;
Postman POST Request
{
"nid": 123,
"host": "localhost",
"url": "http://localhost:1030",
"server": "localhost",
"haserror": true,
"errorcode": 500,
"errordescription": "Not Found"
}
Postman Output
{
"_id": "6299e1de7106c03a3c6cc06c",
"createdAt": "2022-06-03T10:26:38.494Z",
"updatedAt": "2022-06-03T10:26:38.494Z",
"__v": 0
}
Postman Request & Output Image
Record Created in Database
{ "_id" : ObjectId("6299cd8ee20fd12125ec4c16"), "createdAt" : ISODate("2022-06-03T08:59:58.558Z"), "updatedAt" : ISODate("2022-06-03T08:59:58.558Z"), "__v" : 0 }
The code is correct. In postman I was making post request as text instead of json.
i have a server.js which has listening port 4000. Please check below code
const port = 4000;
const express = require('express')
const cors = require('cors')
const app = express()
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "musteri"
});
con.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
app.use(cors());
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
app.listen(port, (err) => {
if(err) { console.log(err) };
console.log('Service Port ' + port + ' started')
})
with above code listening localhost:4000/user
i can access without any problem from chrome when i call localhost:4000/user that returns a record from mysql.
My problem started when i call localhost:4000/user adress from fetch api.
it saying POST http://localhost:4000/user 404 (Not Found)
Here is my fetch code from app.jsx
componentDidMount() {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
},
body: JSON.stringify({ username: "John", password: 30 })
};
fetch(`http://localhost:4000/user`, requestOptions)
.then(handleResponse => handleResponse.text())
.then(user => {
console.log(user);
localStorage.setItem('user', JSON.stringify(user));
return user;
});
}```
What is wrong with my fetchAPI code? Thanks.
app.get('/user', function(req, res, next) {
console.log(req);
con.query('select * from musteri_ayarlar', function (error, results, fields) {
if(error) throw error;
res.send(JSON.stringify(results));
});
});
you have made an get endpoint here to access it
Change the request method in fetch
const requestOptions = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Content-Type': 'applications/json'
}
};
GET doesn't accept any body , as you are not using the request , this will satisfy
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!
I try to send data from my client to my server. For that, i use React with NextJS, because you have the server and client-side in one app.
I use the following handleSubmitFunction:
handleSubmit() {
const email = this.state.email;
fetch('/', {
method: 'POST',
body: email,
});
}
and this is my server.js file in the located in / at my project
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
//parse application
server.use(bodyParser.urlencoded({ extended: false}))
//parse application/json
server.use(bodyParser.json())
server.post('/', (req, res) => {
console.log(req.body.email);
res.end("success!");
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
When the handleSubmit Function is running, i get the following Output from the Server Console:
Cannot read property 'email' of undefined
Where exactly is my mistake?
I have little experience in node JS environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
It seems you have to parse header and JSON.stringify the email.
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then((res)=> console.log('Worked'))