I have a external API request as given below.
Now I need to write this postman API into an axios API call. But I tried to do many alternative things, but nothing seems to work.
The below code explain the current code I tried to do.
const url = `${this._url}/rest/v1.0/files?project_id=${projectId}`;
const response = await Axios.default.post(
url,
{
file: {
parent_id: +parentId,
data: file,
},
},
{
headers: {
Authorization: `Bearer ${updatedToken}`,
'Content-Type': 'multipart/form-data',
'Procore-Company-Id': company.id,
},
maxBodyLength: Infinity,
maxContentLength: Infinity,
}
);
using form-data
const form = new FormData();
form.append( 'my_file', fs.readFileSync('/foo/bar.jpg') );
// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();
axios.post('http://example.com', form, {
headers: {
...formHeaders,
},
})
.then(response => response)
.catch(error => error)
Related
I am having difficulty with figuring out how to send images to my backend. Essentially, my confusion comes from me not knowing what I need my backend to even look like to match my frontend fetch code. My front end code is below:
const onSignUp = () => {
const data = new FormData();
console.log(profilePictureData)
data.append('ProfilePhoto', {
uri: (Platform.OS === 'android' ? profilePictureData.uri : profilePictureData.uri.replace('file://', '')),
type: profilePictureData.type,
name: profilePictureData.fileName
});
const profilePicUrl = `someherokuapi.com/api/photos/profile/me`
fetch(profilePicUrl, {
method: 'POST',
headers: {
'Content-type': 'multipart/form-data',
'Accept': 'application/json',
'x-auth-token': token
},
body: data
})
}
Any help would be much appreciated. Thanks!
Can anyone spot any problems that may explain why the api client is giving me the forbidden error? I know the credentials are correct, as GET requests w the same info in the url work find.
Thank you in advance
app.get('/translate', (req, res) => {
var textToTranslate = "Hello friend"
const targetLanguage = "ES"
var link = `https://api-free.deepl.com/v2/translate`
var options =
{
method: 'POST',
headers: {
"Host": 'api-free.deepl.com',
"Content-Length": 54,
"Content-Type": 'application/x-www-form-urlencoded',
"User-Agent": "YourApp",
"Accept": "*/*",
},
body: JSON.stringify({
'auth_key': deeplAccessCode,
'text': textToTranslate,
'target_lang': targetLanguage
}),
}
return fetch(link, options)
.then((response) => {
console.log(response)
return response.json(); //Transform http body to json
})
.then((json)=> {
res.send(json) //return json to browser
})
.catch(e => {
console.log(e)
return res.sendStatus(400);
});
})
It's probably failing because you're setting your Content-Type of your body to be application/x-www-form-urlencoded (which is correct as per the DeepL API specification) but then you provide a JSON body (which would require content type to be application/json).
You need to provide a URL-encoded body instead, like the part you can also append to the URL after the ?. See also this answer on SO.
i want to send a post request using node-fetch with a body payload encoded in the x-www-form. I tried this code but unfortunately it doesnt work:
paypalSignIn = function(){
var username = process.env.PAYPALID;
var password = process.env.PAYPALSECRET;
var authContent = 'Basic '+base64.encode(username + ":" + password);
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', { method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language' :"en_US",
'Authorization': authContent,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
}
I'm not sure if this way is possible but i need to use this standard for die paypal api.
I'm getting statu code 400 with error
grant_type is null
Thx
I don't know if this is the only error, but at the very least you need a space between the word Basic and the encoded username/password.
Next time you ask a question, also post what your script returned. I'm guessing it was a 401 error in this case.
I used the PayPal sandbox today, here is how I managed to get my access token and a successful response (and also answering the OP's question about sending application/x-www-form-urlencoded POST requests with data) =>
I did it with node-fetch but the plain fetch API should work the same.
import fetch from "node-fetch";
export interface PayPalBusinessAccessTokenResponseInterface {
access_token: string;
}
export interface PayPalClientInterface {
getBusinessAccessToken: (
clientId: string,
clientSecret: string
) => Promise<PayPalBusinessAccessTokenResponseInterface>
}
const paypalClient: PayPalClientInterface = {
async getBusinessAccessToken(
clientId: string,
clientSecret: string
): Promise<PayPalBusinessAccessTokenResponseInterface> {
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
const paypalAPICall = await fetch(
"https://api-m.sandbox.paypal.com/v1/oauth2/token",
{
method: "POST",
body: params,
headers: {
"Authorization": `Basic ${Buffer.from(clientId + ":" + clientSecret).toString('base64')}`
}
}
);
const paypalAPIRes = await paypalAPICall.json();
return paypalAPIRes;
}
};
export default paypalClient;
I'm working on my first app right now which I created in react native for the front end and using Node JS as a backend and mongodb for the database.
I'm trying to implement register form for my user but I don't really know how to do this with the state because it keeps saying cannot evaluation this.state.name.
What I want to do is a POST request using fetch api to register an account it works using Postman so the error come from my front end.
So what I do is I create my function to do that but I want the body to represent the value the user typed in the different field which I store in the state when you'll see the code it will be clear.
If I use the state it does not work however if I put some value directly in my function it works.
This first thing is my function with the fetch API if I do this it does not work, below is how I get the state of each field (see the )
clickthebutton = () =>{
//var data = this.state
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/json'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
}
<Input
label="Your email address"
placeholder="yo#gmail.com"
onChangeText={(text)=> this.setState({email:text})}
value={this.state.email}
>
My state looks like this :
this.state={
email:null,
password:null,
name:null,
age:null,
dataImage:null
}
I would like to send the body, if I do body : this.state it does not send anything when I do a console.log(req.body) on my server it shows an empty object.
Thanks for any help
EDIT : Problem fixed, my function was not referring to my class.
First of all you need a correct element for your email and password inputs, for example (for email):
<TextInput
value={this.state.name}
keyboardType={'email-address'}
placeholder="Your email address"
onChangeText={text => this._onEmailChange(text)}
/>
you also need a function to update the name value (you will need a similar function to update any value coming from a TextInput element)
_onEmailChange = text => {
this.setState({ name: text });
};
Then you can prepare your request as follow
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.name,
password: this.state.password
...
}),
})
.then(response => response.json())
.then(responseJson => {
// do what you want with the response here
})
.catch(error => {
console.error(error);
});
You have specified in the header that you send in json format when you send. When sending to the server, you must convert to jsonString.
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
}),
});
Ok You can try use Formdata
let formdata = new FormData();
formdata.append("name", this.state.name);
formdata.append("age", this.state.age);
formdata.append("password", this.state.password);
formdata.append("email", this.state.email);
fetch('http://localhost:5050/api/new/register', {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(res => res.json())
.then(reponse => {
console.log(reponse)
})
.catch(error => {
console.error(error);
});
After getting all form-data in your state you have two options to make a request to backend.
Either set Content-Type As application/text or remove header.
fetch('http://localhost:5050/api/new/register',{
method:'POST',
headers : {'Content-Type': 'application/text'},
body : {
name:this.state.name,
age:this.state.age,
password:this.state.password,
email:this.state.email
},
})
I am running my React js web app in one port 3000.
For node server I am using 4000.
While calling fetch method it returns `400 Bad request'.
Error
POST http://localhost:4006/auth/admin 400 (Bad Request)
react code npm started in 3000 port
fetch('http://localhost:4000/auth/admin',
{ mode: 'no-cors',
method: "POST",
body: JSON.stringify({
username:"admin",
password:"1234"
}),
headers: {
"Content-Type": "application/json",
'Accept': 'application/json, text/plain, */*',
credentials: "omit", //
// "Content-Type": "application/x-www-form-urlencoded",
},
})
.then((response) => console.log(response));
node code running in 4000 port
const passport = require("passport");
const route = require("../constants/routeStrings");
const keys = require("../config/keys");
const processStatus = require("../constants/processStatus");
const success = {
status: processStatus.SUCCESS
};
const failute = {
status: processStatus.FAILURE
};
module.exports = app => {
app.post('/auth/admin', passport.authenticate("local"), (req, res) => {
res.send(success);
});
};
Do not stringify the body. Change from
body: JSON.stringify({
username:"admin",
password:"1234"
}),
to
body: {
username:"admin",
password:"1234"
},
The 400 response is raised by passport since it is unable to read your params. You need to tell your "node" app to parse them before your actual routes.
// Import body parser, you should read about this on their git to understand it fully
const parser = require('body-parser');
const urlencodedParser = parser.urlencoded({extended : false});
// before your routes
app.use(parser .json());
app.use(urlencodedParser) // This will parse your body and make it available for your routes to use
Then do your other calls.
Also, make sure that you are sending username and password keys, otherwise read the documentation on how to change these key names to something else
I suffered long hours, but I overcame it throw writing those lines of code blocks. I successfully send the request to the server's controller, hopefully yours: make it try.
First define a async function to make POST request:
async function _postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referrer',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(data)
});
return response.json();
}
Now create a request JSON payload:
let requestPayload = {
propertyName1: 'property value1',
propertyName2: 'property value23',
propertyName3: 'property value',
So on
}
Note: Request model will be your desired model, what request payload you actually send.
Now make a request using this payload including your end point URL:
_postData('http://servername/example', requestPayload )
.then(json => {
console.log(json) // Handle success
})
.catch(err => {
console.log(err) // Handle errors
});
100% worked on my project.