I have a scipt tag in which im making a post request to a route through axios.Axios is not sending the parameters through.
Here is the code for axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const data={'firstName':"sai"}
axios({
url: "/",
method: "post",
data: data,
})
.then(response => {
console.log(response);
})
.catch(error => console.error(error));
</script>
Here is the express side of things:
app.post("/",function(req,res){
console.log("post route");
console.log(req.body);
})
Im console.logging the data coming from the post request with the help of req.body(I also have body-parser working just fine.Tested with other normal forms).The req comes through to hit the post route.BUt the body is empty always logs "{}".
Please help me out with this.
Option 1:
Define config object
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
axios.post( uri, params, config )
or
axios({
url,
headers: { 'content-type': 'application/x-www-form-urlencoded' }
data: params
})
Option 2:
Create an api instance (optional) and set default content-type
const api_local = axios.create({
baseURL: 'http://localhost:1000/myapi',
});
api_local.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
api_local.post( uri, params )
I also have body-parser working just fine.Tested with other normal forms
Normal forms submit data encoded as either multipart/form-data or application/x-www-form-urlencoded.
Axios submits data, by default, as application/json.
You need a different body parser. One which supports JSON.
(Or to submit the data in a different format)
Related
I am working on React web app with a Flask backend. how can I send a file with JSON data on the body?
I try the code below but is not working
const file = e.target.file[0]
const user = [{name: 'Ma'}]
const formData = new FormData()
dormData.append('file', file)
dormData.append('user', user)
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})
You have to set the Content-Type header as application/json and you can set the body as your json
Your code would look something like this
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(myJson) //insert your stringified json here
})
Since you are creting a react web app, it's easy to structure a JSON from a form.
You are spelling formData wrong. Use this code:
formData.append('file', file)
formData.append('user', user)
How to send a multipart/form-data from a javascript view to a rails controller?
I'm trying to make a form able to send a file (image) to my backend controller, so I am adding this on the headers of my Axios call:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data';
I add it within my functional component, anyways checking the network i see :
Content-Type: application/json;charset=UTF-8
and the parameters received in the controller are empty (for the file)
I have:
const handlePhoto = (e) => {
const image = new FormData();
image.append('photo', e.target.files[0]);
console.log("inside habdlephoto", image.get('photo'))
const dataSend = Object.assign({} ,data, image.get('photo'));
setData(dataSend)
}
which I use in
<Input
type="file"
innerRef={register}
name="photo"
onChange={handlePhoto}
multiple={true}
/>
the axios call looks like:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
axios
.post("../../../api/v1/products/create.json", { product: {...data, ...dataRegister} }, config )
It seems that you are not setting the headers correctly for the request.
Try to set the headers via the request config:
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
axios.post(url, formData, config)
I mean, i'm trying to make the most simple upload ever, with the following code:
var http = require('http');
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
The point is, if i make a post like this, what it'll post exacly?
Does i need to put at least one header parameter or this create some kind of template?
If i need to put at least one parameter, i would put it into the form.getHeaders"()"?
Through headers you should send HTTP headers of the request as an object
Example code:
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: {
'Accept': 'text/html',
}
});
full list of the header can be found here
You can send data as JSON with the request as follows:
const data = JSON.stringify({
text: 'Hello World'
});
request.write(data);
request.end();
I am trying to upload a file from a react front end to a C# backend. I am using drop zone to get the file and then I call an api helper to post the file but I am getting different errors when I try different things. I am unsure exactly what the headers should be and exactly what I should send but I get two distinct errors. If I do not set the content-type I get 415 (Unsupported Media Type) error. If I do specify content type as multipart/form-data I get a 500 internal server error. I get the same error when the content-type is application/json. The url is being past in and I am certain it is correct. I am unsure if the file should be appended as file[0][0] as I have done or as file[0] as it is an array but I believe it should be the first. Any suggestions welcome :) Here is my api post helper code:
export const uploadAdminFile = (file, path, method = 'POST', resource =
config.defaultResource) => {
const url = createUrl(resource, path);
const data = new FormData();
data.append('file', file[0][0]);
data.append('filename', file[0][0].name);
const request = accessToken =>
fetch(
url,
{
method,
mode: 'cors',
withCredentials: true,
processData: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json', //'multipart/form-data',
Authorization: `Bearer ${accessToken}`,
},
body: data,
})
.then(res => res.json())
.then(success => console.log('API HELPER: file upload success: ', success)
.catch(err => console.log('API HELPER: error during file upload: ', err)));
return sendRequest(request, resource);
};
Thanks for the help and suggestions, it turned out to be a backend issue but even still I learned a lot in the process. I will post my working code here in case anyone comes across this and finds it useful.
export const uploadAdminFile = (file, path, resource=config.defaultResource) => {
const url = createUrl(resource, path);
const formData = new FormData();
formData.append('file', file[0][0]);
formData.append('filename', file[0][0].name);
const request = accessToken =>
fetch(url,
{
method: 'POST',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: formData,
});
return sendRequest(request, resource);
};
As mentioned, the file name does not need to be sent separately and count be omitted. I am indexing the file this way because I get it from dropzone as an array and I only want a single file (the first one in the array). I hope this helps someone else out and here is a link to the mdn fetch docs (good information) and a good article on using fetch and formData.
I'm sending data in my React component via the Fetch API, and returning the result as JSON. When POSTED on my Express server, I use the jsonParser method from bodyParser to parse through the data, but insead I'm only getting back a empty object. I do not understand what's the issue with jsonParser, because if I use textParser, my data get sent fine.
Edit: When printing out the request (req) on the server, it is showing that nothing was received in the body. This only happens with jsonParser though, and not textParser.
Fetch:
fetch('./test',{
method: 'POST',
body: ["{'name':'Justin'}"]
})
.then((result) => {
return result.json();
})
.then((response) => {
console.log(response);
})
.catch(function(error){
//window.location = "./logout";
console.log(error);
});
Express:
app.use('/test', jsonParser, (req,res) =>{
res.json(req.body);
})
Assuming you want to post the {name: 'Justin'} object, you'll want something like
fetch('test', {
method: 'POST',
body: JSON.stringify({name: 'Justin'}),
headers: new Headers({
'Content-Type': 'application/json; charset=utf-8'
})
})
The body parameter does not accept an array (which is what you were passing).
If you did mean to post an array, simply change the body value to
JSON.stringify([{name: 'Justin'}])