I am trying to use an API which is of GET type and it is expecting the data in body, not as query parameter. I am using Axios as HTTP client but it seems Axios is not supporting body in GET request. Since the API is third party, I can not change it to read data from params or change the method to POST.
Is there any way to pass data in body using Axios or any other HTTP Client?
The same API is working with body when using with PHP Curl
Use data or params parameter of the GET according to your needs
Refer the docs for all the parameters
axios.get(< your request url >, {
params: {
custom_data : < Your Body here >
}
}).then(...)
Also Refer
Send object with axios get request
Axios get in url works but with second parameter as object it doesn't
Related
I want to use Mailchimp API in my website so users can enter their email in a field and subscribe to a newsletter. I do not want to use any libraries.
I created a simple form for now with an email field and subscribe button for testing purposes and tried to achieve my goal with XMLHttpRequest. However it does not work, and I am not sure whats wrong or if I need another approach? Is my code structure for the API request correct?
I created a Codesandbox with the code.
If needed I can paste it also here.
It's a back end only API.
You're not supposed to ship this API key with your JavaScript application. It's intended for back end use only, where you can keep the key private.
Probably the issue described in no more detail than "it does not work", is because Mailchimp will block the request if you try to use the key from a browser. Their documentation describes in detail.
Because of the potential security risks associated with exposing account API keys, Mailchimp does not support client-side implementation of our API using CORS requests or including API keys in mobile apps.
If you still want to use the API for this, you'll have to set up your own back end service which receives the data from the front end of your site and forwards it to Mailchimp.
For example, if your website uses PHP, you could preserve your form's JS code, but point it to your own custom endpoint / PHP file instead.
Mailchimp has a PHP client library you could use to make crafting the HTTP request more robust and less verbose. But you could also do it "manually" if you also don't want to install a PHP library.
// form-submission.php
function read_key() {
// Could also come from other source, like environment variables.
// As long as it's in a safe place and can't be leaked.
return file_get_contents(SECRET_KEY_LOCATION);
}
$apiKey = read_key();
require_once('/path/to/MailchimpMarketing/vendor/autoload.php');
$mailchimp = new MailchimpMarketing\ApiClient();
$mailchimp->setConfig([
'apiKey' => $api_key,
'server' => 'YOUR_SERVER_PREFIX'
]);
$response = $mailchimp->lists->addListMember( /* ... form data */);
print_r($response);
Depending on your use case you may need to use one of the many other API endpoints.
The issue is the onSubmit() callback on your "form" element is never executed. In order for the onSubmit() callback on your form to be called upon clicking the "Subscribe" button, the button needs to have a type="submit" attribute on it.
i.e.,
const handleSubmit = () => { ... }
return (
...
<Box
onSubmit={handleSubmit}
>
<TextField ... />
<Button
type="submit" <-- Add this in order to call onSubmit() upon click
>
Subscribe
</Button>
</Box>
...
Edit:
OP is using the MailChimp API from the client. The MailChimp API will not work on the client side. You can only use the MailChimp API on the server side.
However, you can utilize MailChimp's embedded form action URL to subscribe to user's emails on the client side (in a React component). You can avoid the user from being forwarded to MailChimp by sending a fetch POST request with the embedded form action URL.
This below example may need some tweaking, but this is the general idea on how this can be accomplished.
function handleSubmit(event) {
event.preventDefault();
// fetch URL is from MailChimp embedded form action url.
fetch('http://mailchimp.us8.list-manage.com/subscribe/post', {
method: 'POST',
// Not sure if MailChimp used urlencoded or json. You can modify this request to use either.
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'u': 'a123cd45678ef90g7h1j7k9lm', <-- found in embedded form code.
'id': 'ab2c468d10', <-- found in embedded form code.
'MERGE0': email, <-- email to be subscribed.
})
});
}
I am trying to call an API that is given to me. First, I did not understand the question. The API given to me looks like 'test.com/a/b/c/d/d' and it also says: callback parameter name: 'jsonp'. I tried things like adding ?callback='jsonp' at the end of the API and other few things. I am trying to call this API and display the result. I am using React on CodeSandBox and I used the fetch() function to make this call. I keep getting error saying it failed. The API is correct but I just don't understand how I add that callback parameter. I have fetched other JSON based APIs before but this time I am doing something wrong, especially withe this JSONP things. Please help.
Edit** When I put that API in the browser, I do get actual data back. But it in this format /**/invalidCallbackFunctionName([ {DUMMY_DATA1}, {DUMMY_DATA2},.....]) So clearly the API works, it's just that the way I am calling it and the way JSONP works, I am missing something in the code.
Turns out I was not using the right package and the correct way. Here is what works:
import fetchJsonp from "fetch-jsonp";
fetchJsonp("https:/www.a.com/b/c/d", {
jsonpCallback: "jsonp"
})
.then((res) => res.json())
.then((data) => console.log(data));
I am working with Amazon's Mechanical Turk, trying to build an ExternalQuestion site which POSTs data back to AMT using a form-- this is the typical method of passing back answers from an ExternalQuestion, mandated by their API.
Very specifically, I am trying to do this in ReactJS, because it has simplified every other aspect of this project.
Is it possible to get React to POST form data without using an external back-end like Flask/python?
This is an important requirement because as far as I can tell from this information (and my own wasted time), using Flask/python will make the POST data look like it is coming from my server, rather than the Worker's browser, and will get rejected.
And yet, when I look through the React documentation on forms I don't even see a discussion of form methods, like GET and POST. I understand that React is going to want this handled by something like an onClick() function, but I can't see any way to do this in React without making the data look like it's coming from my server rather than Worker's browser.
Your best shot is to use the built in JavaScript Fetch API with the FormData interface.
For the body you can pass in the payload what you can generate with the FormData interface; MDN's documentation on it:
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
Don't use XMLHttpRequest, fetch is the newer that is built on that.
A Generic example with fetch would look like the following:
const formData = new FormData();
formData.append('username', 'abc123');
formData.append('foo', 'bar);
fetch('https://example.com/foo/bar', {
method: 'POST',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', JSON.stringify(response)))
This fetch call then can be called based on a user action like onClick.
Form post is just XHR POST with form-data or x-www-form-urlencoded body and get text/HTML returned. This can be done on React with Axios.
This answer show using Axios to send form-data -> https://stackoverflow.com/a/47630754/3849555
I made an app which uses Wordpress REST API to fetch data and users can manipulate the data and add their own posts from the app.
The app is written in AngularJS and uses http.post method to add a post and http.put to update the existing post. We are using custom posts which are made with Pods plugin.
I am trying to find an action hook which would fire whenever a user makes a http.post or http.put request to the REST API.
So far I tried:
function on_all_status_transitions( $new_status, $old_status, $post ) {
if ( $new_status != $old_status ) {
// A function to perform actions any time any post changes status.
}
}
add_action( 'transition_post_status', 'on_all_status_transitions', 10, 3 );
And also: add_action(save_post)
Thanks in advance!
Have you tried rest_post_dispatch Hook?
Allows modification of the response before returning:
https://developer.wordpress.org/reference/hooks/rest_post_dispatch/
I solved the problem
Turns out the folder where I should save JSON file was not set correctly which caused an error. I checked the error log and that is where I saw what the problem is.
After setting the path to folder correctly the function triggered with action hook worked.
This is the hook I use to trigger the function when the post is updated or a new post is added from the app using http.post or http.put methods:
add_action('pods_api_post_save_pod_item_your_pod_name', 'your_function', 10, 3);
I am using Pods plugin for custom post and this is the action hook from their documentation.
I have below requirement:
Route 1: from(timer:foo?repeatcount=1).recepientList("rest service")
Route 2: from(sourcequeue).process(new myprocessor()).to(destinationqueue)
Need to use the json response from route 1 and pass it to Route 2 processor.
My problem is whenever i set the json response in exchange property and try to use in Route 2 processor it is null.
Any suggestion on how to pass the exchange property between these routes would be of great help.
Thanks in advance.
The reason you cannot use Exchange properties to pass information between routes is that they are not part of the message.
Take a look at this picture of the Camel Exchange model.
When a message is received by Camel, it embeds it into an Exchange and the Exchange is passed through the route. But when you send a message (.to(...)), only the message is sent.
Therefore you have to use (as answered by Thomas) the message body or a message header.
If you use http camel component, the http response should be in the body. You can load it from your processor.
String json = exchange.getIn().getBody(String.class);
from(timer:foo?repeatcount=1).recepientList("http://rest_service")
.to(direct:sourcequeue)
You can also use headers to pass data throw your route.
from(timer:foo?repeatcount=1).recepientList("http://rest_service")
.setHeader(“myJsonResponse”, simple("${body}"))
.to(direct:sourcequeue)
String json = exchange.getIn().getHeader(“myJsonResponse”, String.class);