How can fetch both using json and file? - javascript

I am trying to upload photo message with text to discord webhook using javascript fetch api. How can I upload both my json and file?
var discordWebHookBody = new FormData()
discordWebHookBody.append("map", map)
discordWebHookBody.append("json", {
"username": "Plane-notifier",
"content": content
})
await fetch(this.config.discordWebhookUrl, {
body: JSON.stringify(discordWebHookBody),
method: "POST",
headers: {
"Content-Type": "application/json"
}
});

You can use this json pattern(data) to send with a webhook api call to send message with photo.
const url = "webhook url"
const data = {
"content": "Your Text here.",
"embeds": [
{
"image": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png"
}
}
]
};
const customHeaders = {
"Content-Type": "application/json",
}
fetch(url, {
method: "POST",
headers: customHeaders,
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
});

Related

Why does my request return an ERR_BAD_REQUEST?

I am making a request from postman that returns the requested information without problem, additionally I did the test using curl and in the same way it returns the information successfully.But when doing it from axios it returns an ERR_BAD_REQUEST, the code is the following:
const axios = require('axios');
let payload = {
"payment_method": {
"type": "CARD",
"installments": 2,
"token": "tok_prod_some_token"
}
};
let config = {
method: 'post',
url: 'https://hereismyurl/v1/tokens/cards',
data:payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer pub_prod_some_public_key'
},
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
I can't understand what I'm sending wrong in my request

Getting 400 Bad Request on axios post call

I'm using a url shortner API to test connecting to a API and I keep getting a 400 BadRequest. I've read through a dozen posts here and tried all suggestions and still nothing will work. I don't know what I'm doing wrong.
Function
var axios = require('axios');
module.exports = function (callback, data) {
let url = 'https://cleanuri.com/api/v1/shorten';
let axiosConfig = {
"headers": {
'Content-Type': 'application/json;charset=UTF-8'
}
};
let longUrl = { "url" : data };
axios(url, {
method: "post",
params: {
"url" : data
},
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
I've also tried this and got same error
axios.post(url, JSON.stringify(longUrl), axiosConfig)
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
To send data as body use data field on request options
const payload = { ... }
axios({ ..., data: payload })
params field is used to send query string within url
I have read your api docs https://cleanuri.com/docs.
That requiring your payload send as body, so use data field
Here the snippet:
let payload = { "url" : data };
axios(url, {
method: "post",
data: payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
Edit:
400 Bad Request is indicating your request is invalid (by server)

How can I add raw data body to an axios request?

I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.
I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:
axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
{
headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain' }
}).then((response) => {
this.setState({data:response.data});
console.log(this.state.data);
});
Here I added the content type part. But how can I add the body part?
Thank you.
Edit:
Here is a screenshot of the working Postman request
How about using direct axios API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
You can use postman to generate code. Look at this image. Follow step1 and step 2.
If your endpoint just accepts data that have been sent with Body (in postman), You should send FormData.
var formdata = new FormData();
//add three variable to form
formdata.append("imdbid", "1234");
formdata.append("token", "d48a3c54948b4c4edd9207151ff1c7a3");
formdata.append("rate", "4");
let res = await axios.post("/api/save_rate", formdata);
You can use the below for passing the raw text.
axios.post(
baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
body,
{
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
'Content-Type' : 'text/plain'
}
}
).then(response => {
this.setState({data:response.data});
console.log(this.state.data);
});
Just have your raw text within body or pass it directly within quotes as 'raw text to be sent' in place of body.
The signature of the axios post is axios.post(url[, data[, config]]), so the data is where you pass your request body.
The key is to use "Content-Type": "text/plain" as mentioned by #MadhuBhat.
axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
console.log(response);
});
A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":
axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
console.log(response);
});
C# Controller:
[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
return Ok(code);
}
https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
You can also make a POST with query params if that helps:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
Source: https://stackoverflow.com/a/53501339/3850405
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
You can pass the params like so
await axios.post(URL, {
key:value //Second param will be your body
},
{
headers: {
Authorization: ``,
'Content-Type': 'application/json'
}
this makes it easier to test/mock in Jest as well
I got same problem. So I looked into the axios document.
I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
For sending form data in the body, you can just format the data in url params like this 'grant_type=client_credentials&client_id=12345&client_secret=678910' and attached it to data in the config for axios.
axios.request({
method: 'post',
url: 'http://www.example.com/',
data: 'grant_type=client_credentials&client_id=12345&client_secret=678910',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.
axios.request({
method: 'post',
url: 'http://foo.bar/',
data: {},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
transformRequest: [(data, header) => {
data = 'grant_type=client_credentials'
return data
}]
})
This worked fine for me when trying to send authentication credential in body in raw json format.
let credentials = {
username: "your-username",
password: "your-password",
};
axios
.get(url, { data: credentials })
.then((res) => {
console.log(res.data);
})
Used in React js
let url = `${process.env.REACT_APP_API}/validuser`;
let body = JSON.stringify({
loginid: "admin",
password: "admin",
});
var authOptions = {
method: "post",
url: url,
data: body,
headers: {
"Content-Type": "application/json",
},
json: true,
};
axios(authOptions)
.then((resp) => {
console.log("response :- ",resp);
})
.catch((error) => {
alert(error);
});
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
There many methods to send raw data with a post request. I personally like this one.
const url = "your url"
const data = {key: value}
const headers = {
"Content-Type": "application/json"
}
axios.post(url, data, headers)
let url='<your domain.extension>';
let data= JSON.stringify('mydata');
axios
.get(url, { data })
.then((res) => {
console.log(res.data);
})
For me this solution works, i.e. JSON.stringify(your data) , just convert your raw data using JSON.stringify method.
I hope this works.

React Native "fetch" returning server response without the information

I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.

Email fails to send with SendGrid and POST using JavaScript / TypeScript

I am attempting to send emails with SendGrid's Web API V3. I was able to use Postman to send test emails but it seems Postman doesn't have a way to convert code to plain JavaScript / TypeScript.
My TypeScript is:
emailinvite(){
var payload = {
"personalizations": [
{
"to": [
{
"email": "myemail#service.com"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "from_address#example.com"
},
"content": [
{
"type": "text/plain",
"value": "Hello, World!"
}
]
};
var myHeaders = new Headers({
"Content-Type": "application/json",
"Authorization": "Bearer API_KEY_HERE",
});
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("https://api.sendgrid.com/v3/mail/send",
{
method: "POST",
headers: myHeaders,
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ console.log( JSON.stringify( data ) ) })
}
What am I missing to get this functioning?
In this part:
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
The docs for the FormData API here say that you're setting a key-value pair of json->payload, which is probably not what you want to do... you can probably just do:
fetch("https://api.sendgrid.com/v3/mail/send",
{
method: "POST",
headers: myHeaders,
body: JSON.stringify(payload)
})

Categories

Resources