+ 5
I am extracting some data but i get unexpected end of JSON input at JSON.parse(<anonymous>),why is it so? [Solved]
This is the data I am sending body:JSON.stringify({message:"hii"}), and extracting on the server side through this code let content=[]; req.on('data',(chunk)=>{ content.push(chunk); }); req.on('end',()=>{ console.log(JSON.parse(content).message); })
15 ответов
+ 1
Post first and last name to server, and then get full name. Using vanilla JavaScript and NodeJS core module without any third party libraries.
```client.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:9000/', {
method: 'post',
body: JSON.stringify({
firstName: 'Elon',
lastName: 'Musk'
})
}).then(response => {
return response.json();
}).then(data => {
console.log(data);
document.write(data.fullName);
});
</script>
</body>
</html>
```
```server.js
const http = require('http');
http.createServer((req, res) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST',
/** add other headers as per requirement */
};
if (['POST'].indexOf(req.method) > -1) {
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
let msg = JSON.parse(Buffer.concat(body).toString('utf-8'));
console.log(msg);
res.writeHead(200, headers);
res.end(JSON.stringify({
'fullName': `${msg.firstName} ${msg.lastName}`
}));
return;
});
}
// Handle preflight in CORS
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
}).listen(9000);
```
+ 3
Abhay Out of curiosity, are you using a live debugger where you can step through your NodeJS code from break points to troubleshoot your code at various points in the call stack? Or are you just using console.log(...) at various points to review troubleshooting output?
Debugging will give you a sense of all variables in scope and the state at any given time.
This could help you figure out what the issue is more quickly and independently.
+ 2
Esch actually I tried that string thing then I had to resort to this array ,again tried with string but the same error ,been trying for hours ,still can't resolve this issue :-\
+ 2
Esch I get Typerror:failed to fetch and yes client is using browser but why don't fetch work!?,you are exactly doing the same thing using express with cors enabled rather than what I did ( using createserver and applying headers) but it works for you ,I did heard about axios ,so i will try your method ,thank you :)
+ 2
Abhay Welcome. Fetch api should work. Howerver, I use axios rather than fetch because it has wide browser support.
+ 2
This is fetch version post request from browser.
```client.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:9000/', {
method: 'post',
body: JSON.stringify({
firstName: 'Elon',
lastName: 'Musk'
})
}).then(response => {
return response.json();
}).then(data => {
document.write(data.fullName);
});
</script>
</body>
</html>
```
```server.js
const express = require('express');
const app = express();
const cors = require('cors')
const PORT = 9000;
// CORS-enabled web server
app.use(cors())
app.post('/', function (req, res) {
let body = [];
req.on('data', chunk => {
body.push(chunk)
}).on('end', () => {
let msg = JSON.parse(Buffer.concat(body).toString('utf-8'));
console.log(msg);
res.send(JSON.stringify({
'fullName': `${msg.firstName} ${msg.lastName}`
}));
})
})
app.listen(PORT, function () {
console.log(`server listening on port ${PORT}`)
})
```
+ 2
David Carroll just using console.log ,ty for the advise
+ 1
Esch so I figured out which code is causing the problem ,if you comment out the code above the already commented out code , everything works fine but if you run the following server code using createserver and setting header which I was doing previously, error arises,
https://code.sololearn.com/cZIRVDVt9jkf/?ref=app
So do you have any idea what i might be doing wrong while using createserver and setting headers?
+ 1
Abhay Yes and No. I suspect that headers did not match the request, so the browser did not finish the post request as intended. That's why server receives empty chunk and raises the error. The following code is an example of POST method, using vanilla JavaScript and NodeJS core module without any third party libraries.
+ 1
Esch thanks a lot for taking out time to help me!!,and yes I was as well searching about the issue and came across this statement to check if the method is post and then process the data ,and after that I tried putting
if(req.method!=='OPTIONS') in end event and worked well and after that I saw your answer and it cleared a lot of things for me but here is the thing I don't understand yet=>why 'end' event runs before the 'data' one ?
//So here the end event runs before 'data' that's why the chunk is empty maybe. Because when I added console.logs in 'end' and 'data' event then the one in end ran first with request method being options and than one ran the data event with post method!!
req.on('data',(chunk)=>{
content.push(chunk);
});
req.on('end',()=>{
console.log(JSON.parse(content).message);
0
The structure is right. But type of content variable should be string, not array.
Something likes this,
```
// Prepare a variable for storing message stream whenever "data" is emitted
let content = "";
req.on("data", chunk =>{
content += chunk;
});
// post-processing
req.on("end", ......
```
0
Abhay
It’s weird. If the content is array, this might work.
JSON.parse(Buffer.concat(content).toString()).message
0
Esch didn't,but here is the code through which I am posting Data to server hosted locally,
https://code.sololearn.com/WW67aYc8erQA/?ref=app
Also the following is server code
const http=require("http");
var a={message:"hello"}; http.createServer(function(req,res){
res.setHeader('Access-Control-Allow-Origin','*'); res.setHeader('Access-Control-Allow-Headers','Origin,Content-type') res.setHeader('Access-Control-Allow-Method','POST') res.writeHead(200,{"Content-Type":"text/html"});
res.write(JSON.stringify(a)); res.end();
let content=[];
req.on('data',(chunk)=>{
content.push(chunk);
}); req.on('end',()=>{
JSON.parse(Buffer.concat(content).toString()).message;
})
}).listen(9000);
if you can please try and check it yourself ?
0
Abhay Did the client use a brower to request? If so, what's the error message on the browser?
Also, I use Node requsting Node. It works as it should.
```client.js
// POST first name and last name
const axios = require('axios');
axios.post('http://localhost:9000/', {
firstName: 'Elon',
lastName: 'Musk'
})
.then(res => {
console.log(res.data); // Expect full name "Elon Musk"
})
.catch(function (error) {
console.log(error);
});
```
```server.js
const http = require('http');
http.createServer((req, res) => {
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = JSON.parse(Buffer.concat(body).toString("utf-8"));
console.log('Message from client is ', body);
res.end(`Full name is ${body.firstName} ${body.lastName}`);
});
}).listen(9000);
```
0
In addition. This is browser to node.js server, enable CORS.
```client.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
axios.post('http://localhost:9000/', {
firstName: 'Elon',
lastName: 'Musk'
})
.then(res => {
document.write(res.data); // Expect full name "Elon Musk"
})
.catch(error => console.log(error));
</script>
</body>
</html>
```
```server.js
const express = require('express');
const app = express();
const cors = require('cors')
const PORT = 9000;
// CORS-enabled web server
app.use(cors())
app.post('/', function (req, res) {
let body = [];
req.on('data', chunk => {
body.push(chunk)
}).on('end', () => {
let msg = JSON.parse(Buffer.concat(body).toString('utf-8'));
console.log(msg);
res.send(`Full name is ${msg.firstName} ${msg.lastName}`);
})
})
app.listen(PORT, function () {
console.log(`server listening on port ${PORT}`)
})
```