Is there a limit in the body of a request to an api in React native?Because i cant send large base64 to server - react-native

It says me syntax error: JSON Parse error. unrecognized token '<'
Iam using Fetch to do the request.It let me send short base64 strings i tried so what can i do?
This is my call to the api:
export function uploadPost(post) {
let data = {
body: post.body,
picture: post.picture,
type: post.type,
user: {
_id: post.user._id,
name: post.user.name,
picture: post.user.picture
}
}
var headers = {
'Content-Type': 'application/json',
'Access-Control-Origin': '*'
}
return fetch(URL + "/uploadPost", {
method: "post",
headers: headers,
body: JSON.stringify(data)
})
.then(response => Promise.resolve(response.json()))
.catch(err => {
return Promise.reject(err);
})
}

I finally solved it. The problem was that the response was returning a 413 status and I found out that means payload too large. So I added to my node js express server this lines:
var app = express();
//after
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

Spotify returning 200 on token endpoint, but response data is encoded

I'm working through this tutorial on creating an app that uses the Spotify API. Everything was going great until I got to the callback portion of authenticating using the authentication code flow.
(I do have my callback URL registered in my Spotify app.)
As far as I can tell, my code matches the callback route that this tutorial and others use. Significantly, the http library is axios. Here's the callback method:
app.get("/callback", (req, res) => {
const code = req.query.code || null;
const usp = new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
});
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
data: usp,
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
},
})
.then(response => {
console.log(response.status); // logs 200
console.log(response.data); // logs encoded strings
if (response.status === 200) {
res.send(JSON.stringify(response.data))
} else {
res.send(response);
}
})
.catch((error) => {
res.send(error);
});
Though the response code is 200, here's a sample of what is getting returned in response.data: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003E�˒�0\u0000Ee�uS\u0015��\u000e�(\b\u0012h\u0005tC%\u0010\u0014T\u001e�����0��^޳:���p\u0014Ѻ\u000e��Is�7�:��\u0015l��ᑰ�g�����\u0"
It looks like it's encoded, but I don't know how (I tried base-64 unencoding) or why it isn't just coming back as regular JSON. This isn't just preventing me logging it to the console - I also can't access the fields I expect there to be in the response body, like access_token. Is there some argument I can pass to axios to say 'this should be json?'
Interestingly, if I use the npm 'request' package instead of axios, and pass the 'json: true' argument to it, I'm getting a valid token that I can print out and view as a regular old string. Below is code that works. But I'd really like to understand why my axios method doesn't.
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
res.clearCookie(stateKey);
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
},
headers: {
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token;
const refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { Authorization: 'Bearer ' + access_token },
json: true,
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' + querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}));
} else {
res.redirect(`/#${querystring.stringify({ error: 'invalid_token' })}`);
}
});
});
You need to add Accept-Encoding with application/json in axios.post header.
The default of it is gzip
headers: {
"content-type": "application/x-www-form-urlencoded",
'Accept-Encoding': 'application/json'
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
}

multipart/form-data request failing in react-native

I get the following error when I set the 'Content-Type' as 'multipart/form-data' in react-native.
Below is my code -
const formData = new FormData();
formData.append('org_id', org_id);
formData.append('ans', userAns);
formData.append('remark', userRemark);
formData.append('img', userImg);
files.forEach(file => {
formData.append('files', {
name: file.fileName,
type: file.type,
uri: file.uri,
});
});
const resp = await multiPartInstance({
method: 'PUT',
url: `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
data: formData,
});
return Promise.resolve(true);
I am using axios for calling apis. multiPartInstance is an axios instance -
const multiPartAccessToken = async (config: AxiosRequestConfig) => {
config.headers = {
Accept: 'application/json',
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data;',
};
config.timeout = 30000;
return config;
};
I've tried the above with fetch also but I keep getting the same error. The strangest part is that this request hits the server, server sends a response too but I get this error react-native side. I've noticed if I don't use FormData I don't get any error. But I need to use FormData as I have to upload image files.
Environment Details -
Windows version 21H2 (OS Build 22000.376)
react-native 0.66.3
react 17.0.2
axios ^0.24.0
react-native-image-picker ^4.3.0 (used for selecting images)
Flipper version 0.99.0
I've tried the solutions posted on below forums but they didn't work for me.
request formData to API, gets “Network Error” in axios while uploading image
https://github.com/facebook/react-native/issues/24039
https://github.com/facebook/react-native/issues/28551
I am as follow and works perfectly:
const oFormData = new FormData();
images.map((val, index) => {
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
});
return axios.post(postServiceUrl, oFormData);
Somehow react-native-blob-util doesn't give this error. I modified my code as below -
import ReactNativeBlobUtil from 'react-native-blob-util';
const fileData = files.map(file => {
return {
name: 'files',
data: String(file.base64),
filename: file.fileName,
};
});
try {
const resp = await ReactNativeBlobUtil.fetch(
'PUT',
`${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
{
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data',
},
[
...fileData,
// elements without property `filename` will be sent as plain text
{name: 'org_id', data: String(org_id)},
{name: 'ans', data: String(userAns)},
{name: 'remark', data: String(userRemark)},
{name: 'img', data: String(userImg)},
],
);

Access post body without bodyparser

I am trying to send a bas64 encoded image to my express server and parse it there to save it to disk. Id like to implement this with a simple http post request but couldn't get it to work. My first implementation utilized a websocket server and worked well:
Client:
const object = JSON.stringify({
action: "add_image",
data: dataUrl,
})
ws.send(object)
Server:
ws.on("message", (message) => {
const req = JSON.parse(message);
fs.writeFile(
"path/to/file.png",
data.split(";base64,").pop(),
{ encoding: "base64" },
(err) => err && console.log(err)
)
}
This is my trying to get the same result with an http request.
Client:
const object = JSON.stringify({
action: "add_image",
data: dataUrl,
})
fetch("http://localhost:3001/add_image", {
method: "POST",
headers: new Headers({
Origin: window.origin,
Accept: "image/png",
"Content-Type": "image/png",
}),
mode: "cors",
body: object,
})
Server:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post("/add_image", function (req, res) {
console.log(req.body);
});
Unfortunately, req.body always logs an empty object.
I am not quite sure what I am lacking. Any help would be greatly appreciated.
I found the answer in this article. I needed to combine all individual chunks of the request and then use the data once the process is complete.
app.post("/add_image", function (req, res) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log(JSON.parse(body));
res.end('ok');
});
});

Express CORS response

I am using express to return an api response retrieved via a request call.
router.post('/', function(req, res){
var options = {
...
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody);
res.json(parsedBody)
})
The console log displays the expected payload, also when I use Postman I also see the expected payload.
When though my client app gets the response it is:
Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}
Ive tried adding CORS middleware:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Rquested-With, Content-Type, Accept");
next();
});
My client is a very simple react app using fetch:
fetch('http://localhost:3001/api/', {
method: 'POST',
dataType: 'JSON',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then((response) => {
console.log(response);
}).catch((response) => {
console.log('Error');
});
My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...
{
athlete: {
firstname: "Matt"
...
}
}
How can I just forward on the api request response to the clients fetch success method?
The problem is not CORS related, the response within the react app needed parsing as json:
.then((response) => {
console.log(response.json());
})