Update a wordpress rest api using javascript fetch method - fetch-api

This is the index.php of my plugin where I am registering a custom POST endpoint.
function __construct()
{
add_action('rest_api_init', array($this, 'add_custom_api'));
}
function add_custom_api()
{
register_rest_route('wyr/v1', 'putAns', array(
'methods' => 'POST',
'callback' => array($this, 'putAns')
));
}
But, I want to insert the data inside this endpoint using a fetch post method from javascript.
function putAns($data)
{
return (); // INSERT SOMETHING FROM JAVASCRIPT
}
This is the javascript code that I'm failing with:
async clickHandler(e) {
const response = await fetch("http://localhost/plugdev/wp-json/wyr/v1/putAns", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'A blog post by DAVID',
body: 'Brilliant post on fetch API',
userId: 1,
})
});
var data1 = await response.json();
console.log(data1)
}
There are a lot of other details missing but this is the general gist of the issue: Onclick of a button, I want to change the value of a a property inside this object. Then, I'll have to catch this request from php and insert it into the database.

Related

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API.
I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.
As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:
AxiosError: Request failed with status code 400
The axios(config) method (Which works)
await axios({
method: "POST", // Required, HTTP method, a string, e.g. POST, GET
url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
data: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back"},
},
headers: {"Content-Type": "application/json"},
});
The axios.post() method (Which doesn't works)
let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages"
let payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back my friend"},
}
let headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}
let params = {}
try
{
const resp = await axios.post(url, {payload}, {headers, params});
log("POST RESP",resp)
}
catch(error)
{
throw error;
}
Try below code.
let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';
let payload = {
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': '123456789012',//Recipient Phone Number
'type': 'text',
'text': {
'body': 'Welcome back my friend'
}
};
let headers = {
'Authorization': 'Bearer <Your Temporary access token>',
'Content-Type': 'application/json'
};
axios.post(url, payload, {
headers: headers
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

How to code Multipart-form POST REQUEST using apollo-datasource-rest

I want to code the multipart-form POST REQUEST below using apollo-datasource-rest
My attempt to code this leads to a BAD REQUEST error
const { RESTDataSource } = require('apollo-datasource-rest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
class SalesforceApi extends RESTDataSource {
constructor() {
super();
this.initialize({});
this.getAccessToken()
.then((accessToken) => {
this.headers = {
Authorization: `Bearer ${accessToken}`,
};
});
}
async getAccessToken() {
console.log('Getting Salesforce access token');
try {
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
{
username: 'FILTERED#FILTERED',
password: `${'FILTERED'}`,
grant_type: 'password',
client_id: 'FILTERED',
client_secret: 'FILTERED',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
const { accessToken } = response;
console.log(`ChangeGear sessionId: ${accessToken}`);
return accessToken;
} catch (error) {
console.log(`${error}`);
}
return 'No access token!!!';
}
module.exports = SalesforceApi;
[server:salesforce:local] POST https://test.salesforce.com/services/oauth2/token (343ms)
[server:salesforce:local] Error: 400: Bad Request
If memory serves correctly, form data is serialized slightly differently hence why the FormData interface exists. And the apollo-datasource-rest's this.post method is just a wrapper around fetch, so something like the below should work.
Instead of passing the body as a JSON object, try something like this
const formData = new FormData();
formData.append('username', 'FILTERED#FILTERED');
// ... more append lines for your data
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
formData
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);

Fetch Status Code from restful webservice

I am not able to just fetch the status code from a restful webservice. The web service is just responding with 201 or 401. I am pretty new to react native and I just stuck for hours now.
I am calling the this function in another component. The response I am receiving is always LOG {"_40": 0, "_55": null, "_65": 0, "_72": null}
export default class forgotPasswordCall extends Component {
_forgotPassword = async (username, email) => {
let bodyData = {
'username': username,
'email': email,
}
try {
const response = await fetch('webserviceURL', {
method: "POST",
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(bodyData)
})
return response.status;
}
catch (error) {
console.error(error);
}
}
}
I would need to receive the status code itself.
I would highly recommend using axios instead of fetch. You should try it !

axios post request fails with bad request

I try to do a simple post request with axios.
My code snippet:
const getOauthToken = async () => {
try {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-ProxyPass' : '...',
}
const data = {
...
}
return await axios.post('/oauth2/token', data, {headers: headers});
} catch (error) {
throw new Error(`Unable to get an authentication token. Reason ${error}`);
}
};
This call fails with http 400. When I set the headers as default with
axios.defaults.headers.post['X-ProxyPass'] = '...';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
then it works.
Found the solution in the documentation of axios.
If I use "application/x-www-form-urlencoded", I have to use querystring to serialize in the needed format.
return await axios.post('/oauth2/token', querystring.stringify(data), {headers: headers});
But why it works, when I set the headers as default headers i still mysterious.

Axios OPTIONS instead of POST Request. Express Rest API (CORS)

Im trying to use Axios (and VueJs) to make a Cross Origin POST Request to my Rest Api (running on localhost). Instead of doing a POST request, it actually does a OPTIONS request to my Rest Api. This circumvents a middleware function that checks for a token and return 403.
This is the login function
router.post('/login', (req, res) => {
User.authUser(req.body, (err, user) => {
var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'User nicht gefunden' });
} else if (user) {
if (!passwordIsValid) {
res.json({ success: false, message: 'Falsches Passwort' });
} else {
const payload = {
admin: user.admin
};
var token = jwt.sign(payload, config.secret, {
expiresIn: 86400
});
res.json({success: true, message: 'Token!', token: token});
}
}
})
});
How can I get Axios to make a proper POST request? I tried this hack, because I first thought the OPTIONS Request was just a preflight, but there is no request after I return 200 (or 204)
CORS Middleware:
app.use(function(req, res, next) { //set Response Headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
if ('OPTIONS' == req.method) {
res.send(204);
}
else {
next();
}
});
Axios will sometimes send an OPTIONS request as part of a cors preflight if it doesn't know the Content-Type of a request.
You can get explicitly specify the Content-Type when you build the request, and then it should send your POST request as expected.
Instead of
axios.post(url, params), try:
axios.post(url, params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})