0

Cannot resolve this issue by simple search. If anyone can make that more clear?

In client I've tried attach object to xhr.send(obj). At the moment trying to append to formData object, result the same while... Client code:

var xhr = new XMLHttpRequest() 
xhr.open("post", "/api/test", true)
var formData = new FormData()
formData.append("hi", "hello")
xhr.send(formData)
xhr.onreadystatechange = function() {
 if (this.readyState != 4)
 return
 if (this.status != 200) return console.error(this.status + this.statusText)
 else console.log(this.responseText) 
}

And on back-end I am trying to get req.body this way:

const express = require('express'),
 app = express(),
 http = require('http'),
 path = require('path'),
 bodyParser = require('body-parser') 
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static('public'))
app.get('/', function(req, res) {
 res.sendFile(path.resolve("/public/index.html"))
})
app.post('/api/test', (req, res) => {
 console.log(req.body)
 res.end()
})

Don't see why, but each time I get printed out only empty objects. I've cheked several times front end sends objects.

Appreciate any help.

asked Apr 25, 2016 at 14:08

1 Answer 1

1

You can try to add :

//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Like this express (body parser) understand it have to parse the incoming data.

answered Apr 25, 2016 at 14:10
Sign up to request clarification or add additional context in comments.

1 Comment

So simple =)) thanks a lot. I've been playing around like one hour ))

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.