Posting data to django rest framework using javascript fetch - javascript

I'm trying to post data to my django rest framework using javascript fetch. I've already set up and liked the DRF to my model and got everything set up from the backend. I used the postman app to ensure "get", "post" etc are all working as interned. However, now I'm having problem posting data using javascript to post the data using fetch. I want to add data to my article model which has a "headline", "tag", "content", "background_image" and the user that posted the article.
This is how my code looks like
data = JSON.stringify({
headline: "Testing",
tag: "Testing",
background_image: "Testing",
content: "Testing",
user: 1
})
fetch(
"http://127.0.0.1:8000/api/v1/articlesapi/",
{
method: "post",
headers: {"Authorization":"Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e"},
body: data
}
).then(function(response) {
return response.json();
}).then(function(data) {
console.log("Data is ok", data);
}).catch(function(ex) {
console.log("parsing failed", ex);
})
However, I keep getting the error parsing failed TypeError: Failed to fetch. Does anybody know what I'm doing wrong ?

Please add "Content Type" and "Accept" properties in your header, I think it could be a reason of your error. Let me know if it works :-)
fetch('"http://127.0.0.1:8000/api/v1/articlesapi/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization':'Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e'
},
body: JSON.stringify({data: "your data"})
}).then(res=>res.json())
.then(res => console.log(res));

Related

How do I get the return statement from JavaScript's Fetch?

Now I'm using Fetch to fetch some data from an API in SpringBoot.
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
};
Here is the Java code.
#PostMapping("/addMedicine")
public String addMedicine (#RequestBody Medicine medicine){
return medicineService.addMedicine(medicine);
}
public String addMedicine(Medicine medicine) {
medicineRepository.save(medicine);
System.out.println("Added medicine "+ medicine.getMedicineName());
return "Added medicine "+ medicine.getMedicineName() ;
}
The above methods are from different classes I just put them here to simplify my question.
Now when I use Postman I get the statement like
"Added medicine X"
Now when I post the data from my Frontend app which is in React. I want to get that statement so that I can use it to display something on the page as a confirmation.
How am I going to do it or for more info how does even Postman do it because it looks so easy from them? Please help.
this should work :
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then(data=>{
// Do something ....
})
};

how to capture javascript request payload in php

I am sending a request payload from a javascript function like such
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
fetch('https://www.eg.com/tq.php', {
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: id // i get the id here.
})
});
return window.location.href = "https://www.https://www.eg.com/tq.php";
});
}
}).render('#paypal-button-container');
In my PHP file I want to retrieve that id. I did :
$data = $_POST['orderID'];
AND
$data = json_decode($data);
echo $data->orderID;
AND
even tried changing the url to x-www-form-urlencoded. Still I do not get the value. When I check on the payload I do see the orderID, I also see a 200 OK. Can someone show me what i'm doing wrong? I did research stackoverflow and still can't get this to work. Please help.
fetch function will send GET request if you don't pass method: POST in config explicitly.
That's why you're not getting orderID from $_POST in server-side.
Insert method: "POST" in config like this.
fetch("https://www.eg.com/tq.php", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
orderID: id // i get the id here.
})
});

NodeJS - Send JSON object parameters with node-fetch

I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
and
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
They both result in the following error:
{
"message": "Validation Failed",
"errors": [
{
"resource": "Hook",
"code": "custom",
"message": "Config must contain URL for webhooks"
}
],
"documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}
How do I properly send a JSON object? I'm looking for a solution using node-fetch
When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.
So just add
fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
},
body:JSON.stringify(yourJSON) //here this is how you send your datas
});
And node-fetch will send your body with your request.
If you want more details on that i'll expand my answer
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)

When sending POST request to backend API via fetch(), the body has only key and no value

When I'm sending a POST request to my backend express server, the req.body contains only the key part where the entire body is the key and the value part is empty
This is the frontend fetch request
let data = {
videoUrl: "dummy text"
}
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: JSON.stringify(data)
})
This is how I handle it in backend (NOTE: I'm using body-parser)
app.post("/api/getinfo", (req,res) => {
console.log(req.body);
}
I expect the output to be
'{ "videoUrl":"dummy text" }'
But what I get is
{ '{"videoUrl":"dummy text"}': '' }
The entire requests body is the key, and the value is empty.
What am I doing wrong?
You are using the wrong Content-Type to send json
Try
"Content-Type": "application/json;charset=UTF-8"
I noticed an issue in your header;
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" //this very line
},
I guess what you meant is
fetch("/api/getinfo", {
method:"POST",
headers: {
'Content-type': 'application/json; charset=utf-8'
},
Note: Your header denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. So you need to be sure of what you're writing in your header else you will end up with an error.
I will suggest you get to read more about What does “Content-type: application/json; charset=utf-8” really mean?
The problem is that you are stringifying the data:
body: JSON.stringify(data)
should be
body: data
That should fix it

Instagram authentication API not returning access token

The instagram "server side workflow" for authenticating a user and giving them a session access token doesn't work. First part works in that I can get a code back from here:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
However, when posting this code to
https://api.instagram.com/oauth/access_token
in order to obtain the access token, it just response with "YOU MUST PROVIDE A CLIENT ID", even though I have provided this as part of the form data - the same client id I used to get the code in the first place!
Here is the code I am using:
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: data,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}
Apparently others have reported problems with posting the data as json, which have then been resolved by using "application/x-www-form-urlencoded" - however this doesn't seem to work either now.
Here is the exact error message returned:
{error_type: "OAuthException", code: 400, error_message: "You must provide a
client_id"}
code:400
error_message:"You must provide a client_id"
error_type:"OAuthException"
grant_type should be 'authorization_code'
convert the data object to json format , try
data: JSON.stringify(data),
your code will look like this
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorisation_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
var jsonData= JSON.stringify(data)
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: jsonData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}

Categories

Resources