I want to be able to send data from one server to another, started on the same device (to start with). I have this:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlEncodedParser = bodyParser.urlencoded({extended: false});
app.post('/test', urlEncodedParser, (request, response) =>
{
console.log(request.body);
});
app.listen(9999);
console.log('Server started on port 9999');
const unirest = require('unirest');
unirest.post('http://127.0.0.1:9999/test').headers({'Accept': 'application/json', 'Content-Type': 'application/json'}).send({"test1": 123321, "test2": "321123"})
.then((response) =>
{
console.log(response.body);
});
It looks logical, but console.log(request.body); gives empty object {} yet in the post requests I do send some data using .send. How to get access to that data in the request?
You are sending data with Content-Type: 'application/json', so on the server you need to connect middleware not for urlencoded, but for json. In addition, you do not need to separately connect the body-parser since it is included in express and you can connect the necessary middleware like this:
Server:
const express = require('express');
const app = express();
app.post('/test', express.json(), (request, response) => {
console.log(request.body);
response.end('OK');
});
app.listen(9999, () => console.log('Server started on port 9999'));
Client:
const unirest = require('unirest');
unirest
.post('http://127.0.0.1:9999/test')
.headers({ Accept: 'application/json', 'Content-Type': 'application/json' })
.send({ test1: 123321, test2: '321123' })
.then((response) => {
console.log(response.body);
});
Related
I'm using NextJS for my application and i would like to write an JSON-file to the client in a function. On my localhost everything works fine and without any problem, but the application gets build and deployed to firebase it isn't working anymore.
I already tried multiple things, i already created the function in the api folder of NextJs and also created an localhost node server and call them in nextjs API as:
var fs = require('fs').promises;
export default function (req, res) {
console.log(JSON.stringify(req.body))
let Data= JSON.stringify(req.body)
fetch('http://localhost:9091/data', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: Data
})
.then((response) => {
console.log('here')
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
console.log(text)
res.status(200)
// text is the response body
})
.catch((e) => {
// error in e.message
});
As said this works when the application runs on localhost but not on firebase hosting/functions.
The node server looks like:
var express = require('express');
var app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var fs = require('fs').promises;
app.get('/', function (req, res) {
res.send('Hello World');
})
app.post('/data', function (req, res) {
res.send('Hello World');
let Order = req.body;
console.log(Order)
fs.readFile("object.json",'utf8').then(data =>{
let json = JSON.parse(data);
json.push(Order);
fs.writeFile("object.json", JSON.stringify(json)).then( () => { console.log('Append Success'); })
.catch(err => { console.log("Append Failed: " + err);});
})
})
var server = app.listen(9091, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
What I'm trying to achieve is that data is appended to the JSON file and stored locally on the client.
Does anyone have an idea how to handle this properly?
I am triying to make a post query from my React Native (expo) app to Node.js server (express). And the post is doing nothing. Even, console.log doesnot work. Please, need your help with this
React Native App code:
const options = {
method: 'POST',
timeout: 20000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
a: 10,
b: 20
})
};
fetch(url, options)
.then(response => {
console.log(response.status);
})
.catch(error => console.error('timeout exceeded'));
console.log('3232');
And node.js code:
var express = require('express');
/// create express app
var app = express();
app.use(express.json());
app.post('/g_data/auth', function(req, res){
console.log('LOGGED')
res.send('Hello World!')
});
React Native console return : "3232"
node.js console return nothing
No "new incoming connection detected from ...", "LOGGED", as expected.
Please help, what I am doing wrong?
maybe u need to install and import body-parser on your node js
var express = require('express');
var bodyParser = require('body-parser'); // ++
/// create express app
var app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({extended: false})); // ++
app.post('/g_data/auth', function(req, res){
console.log('LOGGED')
res.send('Hello World!')
});
Ok! the final solution is in wrong Headers. For some reasons, React Native app send Headers:
'Content-Type': 'application/json;charset=UTF-8'
But node.js server receives:
'Content-Type': 'text/plain;charset=UTF-8'
So, first, I have installed cors to server, npm i cors -save and for some reason left Body Parser, and a little bit modernize headers. Here is a final code:
React Native App:
let formdata = '["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]';
///console.log(formdata);
const url = 'http://192.168.88.15:7935/g_data/auth';
const options = {
method: 'POST',
timeout: 20000,
mode:'cors',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: formdata
};
fetch(url, options)
.then((response) => response.json())
/// make design
setLoading(false);
/// next code
console.log('next!');
The server code is:
var express = require('express');
var cors = require('cors')
var bodyParser = require('body-parser');
/// create express app
var app = express();
/// use cors
app.use(cors())
/// use body req parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/g_data/auth', function(req, res){
console.log(req.body)
res.send({Message: 'Hello World!'})
});
app.listen(7935);
console.log('listen port 7935');
I have a simple example of Google App Script sending a post request to my Node application. This is working perfectly.
GAS
function send_webhook_test() {
const url = 'http://my.ip.address/folder'
var body = {msg:'hello from gas'}
var params = {
'method': 'post',
'muteHttpExceptions': true,
'contentType': 'application/json',
'payload':JSON.stringify(body)
};
var res = UrlFetchApp.fetch(url, params);
console.log(res)
}
Node
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
const PORT = 3000
const path = require('path');
app.use(bodyParser.json())
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.post('/', (req, res) => {
console.log(req)
console.log(req.body)
res.status(200).end()
})
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
I would like to change the app.post from ('/') to ('someValue'). So I make the following edit:
GAS
const url = 'http://my.ip.address/folder/someValue'
Node
app.post('/someValue', (req, res) => {
console.log(req)
console.log(req.body)
res.status(200).end()
})
But this returns the error Cannot POST //someValue. How do I correctly change the post url?
Your request is adding a '/'char before the /someValue route.
You can use a middleware to sanitize the path before searching for the routes, or you can review your GAS code to remove the duplicated '/'
I am trying to post the data from react (front end) to nodejs server using axios api call, the url is hit and executes properly, but the the sent data is empty
Node code*
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let corsOptions = {
origin: "*",
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
app.post("/signin",function(request,response,next){
console.log(request);
console.log(request.body);
response.json({});
})
app.listen(4000, "localhost", function () {
console.log("App is listening at port 4000");
});
React Method
onSignin=function(event){
let data = new FormData();
data.append("signinEmail",this.state.signinEmail);
axios({
method:"post",
url:"http://localhost:4000/signin",
data:data,
headers:{
'Content-Type':'multipart/form-data'
}
}).then((res)=>{
console.log(res);
})
}
any help is appreciated.
If you don't need to upload a file in /signin API, you can use 'Content-Type':'application/json' and send a JSON object to the server.
onSignin=function(event){
// data send to server
let data = {
signinEmail : this.state.signinEmail
};
axios({
method:"post",
url:"http://localhost:4000/signin",
data:data,
headers:{
'Content-Type':'application/json'
}
}).then((res)=>{
console.log(res);
})
}
I am currently having a problem with React and Express JS form submit function. It seems like my nodeJS running on port 5000 is receiving an empty object from my ReactJS running on port 8080 using fetch method.
React : Contact.js
handleSubmit(e)
{
e.preventDefault();
var data = {
name: this.state.name,
contact: this.state.contact,
email: this.state.email,
message: this.state.message,
}
var url = 'http://localhost:5000/api/insertUsers';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(data),
})
.catch((error) => {
console.log(error);
});
}
NodeJS : server.js
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
app.listen(5000, () => {
console.log('listening on port 5000');
});
Change the order of bodyparser middleware like this.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
You are sending a request with the content-type of 'application/json' but express is expecting a content-type of 'text/json'. Usually, when req.body is empty content-type is the first suspect you should be looking at.
I am ashamed that I struggled with this for hours. I still haven't gotten it to work with file uploads.
But I did get it to work with a normal form by encoding JSON and sending that along with axios, instead of fetch
My js code
var data = {
id: this.state.id,
}
console.log('data',data)
var bodyFormData = new FormData();
bodyFormData.set('id', this.state.id);
var url = ' http://localhost:3000/get-image-by-id';
console.log("bodyFormData: ", bodyFormData);
axios({
method: 'post',
url: url,
data: data,
// headers: {'Content-Type': 'multipart/form-data' }
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Form Code
<form method="POST" onSubmit={this.handleSubmit} >
<label>
Transaction ID
<input
type="text"
name="id"
value={this.state.id}
onChange={this.handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
```
EDIT
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors'
}).then((result)=>{
console.log("output" + result.json());
})
.catch((error) => {
console.log(error);
});
EDIT 2
for backend, install cors and add the following lines before route.
var cors = require('cors')
app.use(cors())
EDIT 3
perform npm install morgan then copy these lines inside the code
var morgan = require('morgan');
app.use(morgan('dev'));
I didn't look at your code close enough. My bad
app.post('/api/insertUsers', function(req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
Should be
app.post('/api/insertUsers', function(req, res) {
res.json(req.body)
});
try using axios instead of fetch
I rewrote ur code like this and it works perfectly
server
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/insertUsers', function(req, res) {
// console.log(req);
console.log(req.body);
res.send(req.body);
});
app.listen(3001, () => {
console.log('listening on port 3001');
});
react (ensure you have axios installed)
handleSubmit(e){
e.preventDefault();
var data = {
name: "zadiki",
contact: "0702002109",
email: "zadiki",
message: "test",
}
console.log("wow");
var url = ' http://localhost:3001/api/insertUsers';
axios.post(url,data)
.then(response=>console.log(response))
.catch(e=>console.log(e))
}
Hello I ended up getting mine working after I ran into the same problem.
I noticed your react code has "mode: 'no-cors'," that was causing problems with mine so I removed it.
-------- Below is my handle submit code for React ------------
const handleSubmit = (event) => {
event.preventDefault();
const url = "http://localhost:3001/register"
const options = {
method: "POST",
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
}
fetch(url, options)
.then(res => res.json())
.then(res => console.log(res))
}
I used express.json instead of bodyParser. You also had a typo in your express code, it should say res.send instead of res.end
--------- Below is my Node Express Code -----------
const express = require('express');
const app = express();
const cors = require('cors');
const multer = require('multer');
// Middlewares
app.use(cors({ origin: 'http://localhost:3000', }))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(multer().array());
app.post('/register',(req, res) => {
console.log(req.body)
res.status(200)
.json({status:"Success", data:{body: req.body })
});
app.listen(3001, () => console.log(`Running on 3001`))
I was able to send form data using postman and react using the code above. Feel free to change it to accommodate your needs.