I use nextjs API Routes to connect to an external API
when I use a POST request to send a file, the file doesn't handled correctly in API Routes and I get 422 Unprocessable Entity Error
when I send only text it's OK, but when I add a file this error occur.
my request
const data = new FormData();
data.append('first_name', firstName);
data.append('last_name', lastName);
data.append('phone_number', phoneNumber);
image && data.append('avatar', image);
axios.post(`${API_ROUTE}`, data, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res=>{
alert(JSON.stringify(res.data, null, 2));
})
my API Route
const config = {
headers: {
'Content-Type': req.headers['content-type']
}
};
axios.post(address, req.body, config)
.then(r=>{
res.statusCode = 200
res.json( r.data )
})
.catch(err=>{
res.json(err)
})
in the request that API Route sending to the external API, there are some ? in the content of the file, but in the request that sending from browser to the API Route seems there are different characters
Related
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);
so I have an API with an endpoint that returns an xlsx file on post request
when I call that API from nextjs server side API it returns a corrupted zip file
but when I call it directly through postman it returns the expected xlsx file.
the call to the API from nextns looks like this:
axios.post(`${process.env.API_URI}`, formData, {
headers: {
...formData.getHeaders(),
},
responseType:"blob"
}).then(response => {
res.status(200).send(response.data)
tmpObj.removeCallback()
}).catch(err => {
console.log(err)
tmpObj.removeCallback()
})
is there a proper way to receive the xlsx file in nextjs API ... Nodejs
update:
eventually I had to set the Content-Type in axios header and the responseType in axios config object
axios.post(`${process.env.API_URI}`, formData, {
headers: {
...formData.getHeaders(),
'Content-Type': 'blob',
},
responseType:"arraybuffer"
}).then(response => {
//createthe buffer in the frontend const buffer = Buffer.from(response.data, 'base64');
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
// res.setHeader('Content-Disposition', 'attachment;filename=SheetJSNode.xlsx')
res.status(200).send(response.data)
}).catch(err => {
console.log(err)
})
I am working on MERN stack and I have made an api for registering users. I am using axios to send request this is what i am doing with axios inside react
const body = {
'phone': phoneData.phoneNumber, \\ phoneData is a state
'lastName': 'Flintstone'
}
await axios({
method : 'post',
url : 'http://localhost:8000/userapi/register',
data : JSON.stringify(body),
header : {'Content-Type': 'application/json'}
});
After this in NodeJS i am trying to print req.body on the console an this is what i am receiving
{ '{"phone":"7428868740","lastName":"Flintstone"}': '' }
instead of that i want req.body to store
{ phone:"7428868740",lastName:"Flintstone" }
This is my route that is getting triggered
app.post('/userapi/register', (req,res) =>{
console.log(req.body);
/* rest code to register user */
}
With Axios, you don't need to call JSON.stringify, just send the object and the server will receive it correctly.
const body = {
'phone': phoneData.phoneNumber, // phoneData is a state
'lastName': 'Flintstone'
}
await axios({
method : 'post',
url : 'http://localhost:8000/userapi/register',
data : body,
headers : {'Content-Type': 'application/json'}
});
See documentation here
On the server-side, make sure there is a middleware to parse requests in JSON format.
You can
const config = {
header: {
"Content-Type": "application/json",
},
};
const res = await axios.post(url,body,config)
I'm try to pass the 'token_mailchimp' from axios get request to nodejs request get
For the moment i pass the auth token from a variable directly in app.js in my node/express project.
app.js in node/express project
app.get('/mailchimp/campaigns', checkAuth, function (req, res) {
request
.get('https://' + mailchimpInstance + '.api.mailchimp.com/3.0/campaigns')
.set('Content-Type', 'application/json;charset=utf-8')
.set('Authorization', 'Basic '+token_mailchimp)
.end((err, result) => {
if (err) {
res.status(500).json(err);
} else {
res.json(result.body);
}
});
});
axios get request in ReactJS project
.get('http://localhost:8081/mailchimp/campaigns',
{ headers: {"Authorization" : `Bearer `+jwt_token} })
.then(({ data })=> {
this.setState({
campaigns: data.campaigns
});
})
.catch((err)=> {})
How can i pass from axios request the auth token for the request /mailchimp/campaigns?
You can send a new custom header like x-api-token
{ headers: {"Authorization" : Bearer+jwt_token, "x-api-token" : "your_token"} }
Then in the app.js, access the headers from the request,
const {headers} = req;
Then use that in your API request
.set('Authorization',`Basic ${headers["x-api-token"]}`)
Note: If you are using cors plugin then make sure it's allowing that header to pass.
You can add header x-api-token manually in cors configuration if needed.
I am trying to handle various http status codes from my node/express and pass the response back to the angular. i get an error that Cannot set Headers after they are sent to the client. How do i Handle this based on response and also log for various http codes in nodejs?
app.post("/employees", function(req,res) {
var ServerOptions = {
method: 'POST',
uri: 'http://localhost:5001/api/empData',
body: req.body,
json: true,
headers: {
'Content-Type': 'application/json'
}
};
request(ServerOptions).then(function (Response) {
res.status(200).json(response);
})
.catch(function (err) {
res.status(401).json({message: "unauthorized"});
console.log("Unauthorized");
res.status(404 || 500).json({message: "error"});
console.log("Error");
res.set("Connection", "close");
});
});
According to angularjs documentation on $http, when server returns status other than 200, "error" callback is invoked.
Try placing your code for handling 401 status inside .error().