Posting data using node-fetch in a react component malfunction - node.js

I'm simply trying to post json data to an express server using node-fetch. I know the post function in the server works because I've tested it in git bash. I'm also doing this in a react component.
Here's the fetch code:
addBug(bug) {
let bugsModified = this.state.bugs.slice()
bug.id = this.state.bugs.length + 1
bugsModified.push(bug)
fetch('http://localhost:3000/api/bugs', {method: 'POST', body: bugsModified})
.then(res => res.status === 200 && this.setState({bugs: bugsModified}))
}
The {body: bugsModified} doesn't seem to send the server anything. Here's the code from the server:
app.use(bodyParser.json())
app.post('/api/bugs', (req, res) => {
const bug = req.body
bugs.push(bug)
res.json(bug)
})
app.listen(3000, () => console.log('connected...'))
If anyone can help me figure out how to post actual data using node-fetch, it would be greatly appreciated.

FYI I would ensure that your content headers are populated:
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': new Buffer(body).length
}

Related

Nodejs + Axios Post returns undefined value

I am using React + NodeJS & Axios but have been trying to send a post request but experiencing difficulties.
The request seems to be posting successfully, but all actions at the nodejs server is returning in the "undefined" data value, even if the data is passed successfully shown in the console.
REACT
const fireAction = (data1, data2) => {
const data = JSON.stringify({data1, data2})
const url = `http://localhost:5000/data/corr/fire`;
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'AUTHCODE',
}
}
axios.post(url, data, config)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
fireAction("Oklahoma", "Small apartment")
NODE
app.post('/data/corr/fire', async (req, res) => {
try {
const data = req.body.data1;
console.log(data)
} catch(e) {
res.send({success: "none", error: e.message})
}
});
Result of node: "undefined"
I have added the following body parser:
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
I am not sure why this error is happening. I see there is similar questions to mine: however none of them are applicable as I'm using both express and body parser which is already suggested.
You're POSTing JSON with a content-type meant for forms. There's no need to manually set content-type if you're sending JSON, but if you want to manually override it, you can use 'Content-Type': 'application/json', and access the response in your route with req.body. If it does need to be formencoded, you'll need to build the form:
const params = new URLSearchParams();
params.append('data1', data1);
params.append('data2', data2);
axios.post(url, params, config);

Node.js? API Authentication problems

This is what my "dev" sent me. Someone help please
I'm trying my best, but their API doesn't respond to our methods. This authentication is the root of the problem. I'm right now using Axios(the most popular and only method for making API requests for web apps) but it's not accepting request
and then i told him i would ask for help*
You can ask this question- ` How do I make requests for creating order API in my express app? I've tried to make the request by getting my form data from my EJS form using the request.body. But still, it is saying error 400.
Here is his code:
app.post('/order-labels', checkAuthenticated, (req, res) => {
const data = JSON.stringify(req.body);
console.log(data)
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
})
by console.logging we are getting the data, but the API doesn't accepting
The API Docs are here.
you may need an account to view just put junk
The API calls for url encoded string.
const data = JSON.stringify(req.body);
console.log(data)
data = new URLSearchParams(Object.entries(data)).toString();
console.log(data); // now should be URL encoded
const config = {
method: 'post',
url: 'https://labelsupply.io/api/order',
headers: {
'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
See if the API likes the new encoding?

Angular 7 / Express - Null response body on POST request

I'm trying to get/read the response from a POST request made in Angular 7, if I set the API to return "text" everything is OK, but when i make the response a JSON the response body on Angular is null.
If I try the API on Postman I get full response JSON body.
I tried changing response method on Express API (from the simple res.json() to the "old" way of declaring Content-Type and sending it with res.end()), nothing changed.
The response code I'm using on backend:
res.status(200).json({
success: true,
token: token
})
What I also tried:
res.writeHead(200, { 'Content-Type': 'application/json' })
var json = JSON.stringify({
success: true,
token: token
})
res.end(json)
The service I'm using on Angular:
login(username: string, password: string): Observable<any> {
let body = {username: username, password: password};
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
return this.http.post(this.baseUrl + "/login/sign-in", body, {headers: headers, responseType: 'json', observe: 'response'});
}
The call to that service:
this.api.login("admin", "password").subscribe(result => {
console.log(result);
})
On Postman I get this result:
On Angular I get this (JSON):
On Angular I get this (TEXT):
Edit:
If I add anything before the JSON on the Express app, the body is no more null:
res.writeHead(200, { 'Content-Type': 'application/json' })
var json = JSON.stringify({
success: true,
token: token
})
res.end('some_char' + json)
The result (of course the response goes in error):
Edit 2:
I'm also trying (with no luck) with this simple version of the endpoint:
const express = require('express')
const app = express()
app.post('/login/sign-in', (req, res) => res.json({ value: 1 }))
app.listen(3000, () => {
console.log('App running on port 3000.')
})
Solution:
It was all a CORS problem, I added this to the backend and everything is working fine:
app.use(cors())
Spent a few minutes trying to find out why the body would be empty,
In my case, I had "mode":"no-cors" set in my fetch() options, therefore the returned value from the server would appear as "opaque"
redux fetch body is not use with no cors mode
I hope this can help !

Difficulties with posting data to Google Firebase HTTP Functions

I am trying to POST some variables as part of req.body to a Firebase Cloud Function. I am using the modern fetch() syntax as following:
const { licenseCode } = this.state;
fetch('https://myAPI.com/inputLicense', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ licenseCode })
})
And here is how my Cloud function looks:
exports.inputLicense = functions.https.onRequest((request, response) => {
// const { licenseCode } = request.body
console.log(request.get('content-type'))
console.log('query', request.query)
console.log('body', request.body)
})
Unfortunately, all of the above logging produces empty objects or undefined in the case of the first line. In a usual Express setup, I know I need to use:
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
But don't know how to do it with cloud functions. Google claims in their Docs they parse my requests automatically, based on the header but I just can't get it to work.
Any help is more then welcome, thanks in advance.
It seems like you solved the problem, but for anyone else having a problem. In my case the problem was the firebase cloud function triggering on the cors preflight request which contains no body.
I solved it by removing the application/json content-type in the fetch call and decoding the json body manually in the cloud function
// on the client
fetch(functionURL + '/' + name, {
body: JSON.stringify({abc: 123}),
method: 'POST',
mode: 'cors',
})
// on the server
functions.https.onRequest(async (req, res) => {
const {abc} = JSON.parse(req.body)
res.set('content-type', 'application/json')
res.set('Access-Control-Allow-Origin', '*')
res.status(200)
res.send({result: abc})
})
I've done some tests and apparently the problem comes from the object destructuring.
The following should work:
const obj = { licenseCode: this.state };
fetch('https://myAPI.com/inputLicense', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(obj)
})

Node JS upload file streams over HTTP

I'm switching one of my projects from request over to something a bit more light-weight (such as got, axios, or fetch). Everything is going smoothly, however, I'm having an issue when attempting to upload a file stream (PUT and POST). It works fine with the request package, but any of the other three return a 500 from the server.
I know that a 500 generally means an issue on the server's end, but it is consistent only with the HTTP packages that I'm testing out. When I revert my code to use request, it works fine.
Here is my current Request code:
Request.put(`http://endpoint.com`, {
headers: {
Authorization: `Bearer ${account.token.access_token}`
},
formData: {
content: fs.createReadStream(localPath)
}
}, (err, response, body) => {
if (err) {
return callback(err);
}
return callback(null, body);
});
And here is one of the attempts using another package (in this case, got):
got.put(`http://endpoint.com`, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${account.token.access_token}`,
},
body: {
content: fs.createReadStream(localPath)
}
})
.then(response => {
return callback(null, response.body);
})
.catch(err => {
return callback(err);
});
Per the got documentation, I've also tried using the form-data package in conjunction with it according to its example and I still get the same issue.
The only difference between these 2 I can gather is with got I do have to manually specify the Content-Type header otherwise the endpoint does give me a proper error on that. Otherwise, I'm not sure how the 2 packages are constructing the body with the stream, but as I said, fetch and axios are also producing the exact same error as got.
If you want any of the snippets using fetch or axios I'd be happy to post them as well.
I know this question was asked a while ago, but I too am missing the simple pipe support from the request package
const request = require('request');
request
.get("https://res.cloudinary.com/demo/image/upload/sample.jpg")
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
and had to do some experimenting to find similar features from current libraries.
Unfortunately, I haven't worked with "got" but I hope the following 2 examples help someone else that are interested in working with the Native http/https libraries or the popular axios library
HTTP/HTTPS
Supports piping!
const http = require('http');
const https = require('https');
console.log("[i] Test pass-through: http/https");
// Note: http/https must match URL protocol
https.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
(imageStream) => {
console.log(" [i] Received stream");
imageStream.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
);
}
);
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
)
Axios
Note the usage of imageStream.data and that it's being attached to data in the Axios config.
const axios = require('axios');
(async function selfInvokingFunction() {
console.log("[i] Test pass-through: axios");
const imageStream = await axios.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
{
responseType: "stream", // Important to ensure axios provides stream
}
);
console.log(" [i] Received stream");
const upload = await axios({
method: "post",
url: "http://127.0.0.1:8000/api/upload/stream/",
data: imageStream.data,
headers: {
"Content-Type": imageStream.headers["content-type"],
},
});
console.log("Upload response", upload.data);
})();
Looks like this was a headers issue. If I use the headers directly from FormData (i.e., headers: form.getHeaders()) and just add in my additional headers afterwards (Authorization), then this ends up working just fine.
For me just works when I added other parameters on FormData.
before
const form = new FormData();
form.append('file', fileStream);
after
const form = new FormData();
form.append('file', fileStream, 'my-whatever-file-name.mp4');
So that way I can send stream from my backend to another backend in node, waiting a file in multipart/form-data called 'file'

Resources