I have a simple express graphql server:
const schema = require('./schema');
const express = require('express');
const graphqlHTTP = require('express-graphql');
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP(req => {
return ({
schema,
pretty: true,
})
}));
const server = app.listen(9000, err => {
if (err) { return err; }
console.log(`GraphQL server running on http://localhost:${9000}/graphql`);
});
And my request looks like:
Any help?
(Please don't close it as duplicate because the other post does not provide enough info on how the user solved it)
You need to specify application/json in your Content-Type header -- you currently have text/plain. You've included the body parser middleware on the server, but it relies on that header in your request to know when it needs to actually parse the response into JSON.
Related
Im new in express.js so i would like to know why when I'm sending a data to client the data is showing in the browser but I'd like to send it in preview please can you take a look what I do wrong?
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/getProducts', (req,res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type','application/json');
res.json(obj);
});
first you need install dependencies like body-parse cors, then you need listen port like this
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/getProducts', (req, res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type', 'application/json');
res.json(obj);
});
app.listen(3000)
I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine
I am having trouble access the body parameters of a request with express:
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const app = express();
const port = 8000;
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
const corsOptions = {
origin: 'http://localhost:8000'
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, () => console.log(`Listening on http://loclalhost:${port}`));
The route I am trying to hit is: http://loclalhost:8000/api/auth/signup
Within the route I try to access the body like so:
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
});
However I am getting the error TypeError: Cannot read property 'username' of undefined, what am I doing wrong here?
I guess the problem is not in reading the body parsed data, as it says user and not username. Can you please share the complete code instead.
A suggestion
Change :
app.use(bodyParser.urlencoded({ extended: true }))
to
app.use(bodyParser.urlencoded({ extended: false }))
and use x-www-form-urlencoded
Hmm well my guess is the order how you wrote your code. Imagine the code goes from the top to the bottom, so you access the app routes before you parse the body. Try it like this, swap the order:
const corsOptions = {
origin: 'http://localhost:8000'
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
Its also a common way to use the express router like this for example:
const routes = require("./routes/routes.js");
app.use(routes);
I am trying to set up a very simple javascript server however I cant even properly get the data from a post request!
Here is what I am doing. I have annotated what works and what doesn't. Essentially everything except for the post request works perfectly. Unfortunately the body of the request is always empty resulting in garbage information.
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }))
const mongoUrl = '<DBAddress Goes Here>';
MongoClient.connect(mongoUrl, (err, mongoDb) => {
if(!err) {
db = mongoDb;
console.log("Connected correctly to server");//This always happen successfully
}
});
app.listen(80);
app.get('/test', function(req, res) {
res.json({ data1: 11, data2: 4, data3: 9 }); //This always works!
});
app.post('/update', function(req, res) {
const params = req.body;
console.log(req.body);//Empty
console.log("Parameters");
const newReport = {
id: params.id,
data: params.data
};
console.log(newReport);//Nothing is put in here
});
I am testing this post request in Postman with website.com/update as the address and the proper fields in the body part of the post.
You need to parse request body in order to get the body in req.body.
As you are already using body-parser package just add the following line after your urlEncoded middleware. and remember the order of middleware matters in the express.
app.use(bodyParser.json());
add above line right after this
app.use(bodyParser.urlencoded({ extended: false }))
And make sure that you are sending data in the JSON format as by default postman send data in plain format
Somehow my req.body is always empty, maybe you have an idea:
here is my server code:
const Express = require('express');
const bodyParser = require('body-parser');
const app = new Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/save', (req, res) => {
console.log(req.body) // => {}
res.send(req.body);
});
const env = process.env.NODE_ENV || 'production';
app.listen(3000, err => {
if (err) { return console.error(err); }
console.info(`Server running on http://localhost:${port} [${env}]`);
});
When I try to send formdata with javascript the req.body is empty:
const data = new FormData(document.querySelector('form'));
console.log(data); // seems empty already??? FormData{}??
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/save');
xhr.send(data);
Same with postman:
I don’t understand this…
Sending x-www-form-urlencoded with postman or raw (application/json) works in postman. But sending the same headers with Formdata in javascript will still result in an empty object…
To log every field in formData
let myForm = document.getElementById('myForm');
formData = new FormData(myForm);
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
Fiddle - https://jsfiddle.net/thesumit67/j4znhxa5/1/
To handle it via express use multer.
Here is an example -
https://www.npmjs.com/package/multer
Make sure to add enctype="multipart/form-data" on form element. Otherwise Multer will ignore it.
let multer = require('multer');
let upload = multer();
app.post('/save', upload.fields([]), (req, res) => {
console.log( req.body );
console.log( req.files );
res.sendStatus(200);
});
body-parser is deprecated and isn't a part of Express anymore.
Also, body-parser does not provide the functionality to parse form-data post data.
From the body-parser repository description:
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
busboy and
connect-busboy
multiparty and
connect-multiparty
formidable
multer
From what I understand, the problem may be in the HTML form.
<form action="" method="POST">
<input type="text" name="foo[bar]">
<button>Submit</button>
</form>
Then in the server code it may look something like this.
app.post('/save', (req, res) => {
console.log(req.body.foo) // => {}
res.send(req.body.foo);
});
Again, this post is older so you've probably already fixed it.
I had this same problem, I was using the fetch api, sending form data to an node.js/express backend. The problem was that I had set enctype='multipart/form-data' on the form and I was also setting Content-type: multipart/form-data in the fetch Headers.
Removing the Content-type from the Headers got everything to work.
I got the solution from here => https://github.com/expressjs/multer/issues/411
Express and body parser Version :
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
app.js:
const express = require('express');
var bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use( bodyParser.json());
const baseUrl = '/api/v1/tours';
app.post(baseUrl, (req, res)=>{
console.log(req.body);
res.send('Done');
})
//starting server
const port = 3000;
app.listen(port, ()=>{
console.log(`app running on port ${port}...`);
});
To send raw data please select JSON from the list