I have a nodeJS app
I'm trying to send the user-agent value that I got from the client side using navigator.userAgent
to the server side using ajax.
PS : I know I can access the user-agent from the server. I am aware of that. I am doing this for a certain purpose.
As follows :
window.addEventListener('DOMContentLoaded', async() => {
$.ajax({
type:'POST',
url:'/UA/send/',
data: navigator.userAgent })
});
In my nodeJS server, I am reading it like that:
app.post('/UA/send', function(req, res)
{
console.log(req.body));
});
This returns
{ 'Mozilla/5.0 (X11; Linux x86_64) Chrome/64.0.3282.140 Safari/537.36': '' }
I added alert(navigator.userAgent);
to my javascript code and I got this :
Mozilla/5.0 (X11; Linux x86_64) Chrome/64.0.3282.140 Safari/537.36
Why am I getting it in the following format to the server side? And how could I parse and read it?
When posting a JSON using $.ajax
, you have to use JSON.stringify
, and 'Content-Type': 'application/json'
header, otherwise you're sending form data. In your example you were sending the user agent as key, and no value.
That's why the posted object looked like: { [userAgentValue]: ''}
Use this for posting a JSON.
$.ajax({
type:'POST',
url:'/UA/send/',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ userAgent: navigator.userAgent })
});
With the correct body parser on your server:
app.use(bodyParser.json());
Now you will receive:
{ userAgent: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/64.0.3282.140 Safari/537.36' }
If you're not trying to post a JSON, and you're using: application/x-www-form-urlencoded
$.ajax({
type:'POST',
url:'/UA/send/',
data: { userAgent: navigator.userAgent }
});
And on your server:
app.use(bodyParser.urlencoded({ extended: false }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.