response of react native get request gets status text undefined - http

I'm new to React Native and I'm calling an API with params. It looks like this.
async onSendClick() {
AsyncStorage.getItem('#Token:key').then((token) => {
console.log("console is " + token)
let subject = "Feedback Form"
let senderEmail = 'test#test.com'
let fromEmail = 'us#test.com'
let replyTo = 'customer#test.com'
let url = BASE_URL + '/email/send?'
let params = "subject=" + subject + "&email=" +senderEmail + "&fromEmail=" + fromEmail + "&replyTo=" + replyTo + "&content=" + feedBackMessage
return fetch(url + params , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
}).then((responseOne) => {
console.log(responseOne)
if (responseOne.status == 200) {
console.log("success")
} else{
console.log("error")
}
}).catch((error) => console.error("ERROR" + error));
})
}
In the response section , I'm getting 404 error with statusText: undefined. Please help me to fix this issue.

You must encode the URI. Otherwise it will not work.
Follow this link for more info about URL encoding in javascript.

Related

My http request not working with mailgun api

header = ds_map_create();
header[? "Content-Type"] = "application/json";
header[? "api"] = "My api key that im censoring :)";
json = ds_map_create()
{
json[? "from"] = "mailgun#lapaihui.org";
json[? "to"] = "My email that im also censoring :]";
json[? "subject"] = "Dear user";
json[? "text"] = "This is your game talking";
}
http_request("https://api.mailgun.net/v3/lapaihui.org/messages","POST",header,json);
basically im trying to send an email using mailgun api but something is just not working
if any netcode gods can help i will greatly apreciete it and credit it!
Without any information on the error you getting or why it's not working, I can't be certain what you need, but I have two working solutions that will hopefully help.
If you're sending from the browser:
function sendMgEmail(pFrom, pTo, pSubject, pText, mgApiKey){
const formData = new FormData();
formData.append('from', pFrom);
formData.append('to', pTo);
formData.append('subject', pSubject);
formData.append('text', pText);
const qXhr = new XMLHttpRequest;
const qMethod = 'POST';
const qUrl = 'https://api.mailgun.net/v3/{{YOUR_DOMAIN}}/messages';
qXhr.open(qMethod, qUrl);
qXhr.setRequestHeader('Authorization', 'Basic ' + window.btoa('api:' + mgApiKey));
qXhr.send(formData);
qXhr.onload = function() {
if(qXhr.status == '200' || qXhr.status == '201') {
console.log('email queued', qXhr.status, qXhr.responseText);
} else {
console.log('ERROR ', qXhr.status, qXhr.responseText);
}
}
}
If from a Nodejs application, the XMLHttpRequest approach does not seem to work:
First, refer to https://www.npmjs.com/package/mailgun.js?utm_source=recordnotfound.com#messages
Then, install form-data and mailgun.js
npm i form-data
npm i mailgun.js
Lastly, the code...
const FormData = require('form-data');
const Mailgun = require('mailgun.js');
exports.sendMgEmail(pFrom, pTo, pSubject, pText, mgApiKey) {
const mailgun = new Mailgun(FormData);
const mg = mailgun.client({username: 'api', key: mgApiKey})
mg.messages.create('{{YOUR_DOMAIN}}', {
from: pFrom,
to: pTo,
subject: pSubject,
text: pText
})
.then(msg => console.log(msg))
.catch(err => console.error(err));
}

WooCommerce REST API with Google UrlFetchApp header authorization not working

CURRENTLY
I am utilising WooCommerce REST API in my Google Scripts with the following working code:
var ck = "ck_longstringlongstringlongstringlongstring";
var cs = "cs_longstringlongstringlongstringlongstring";
var website = "https://www.mywebsite.com.au";
var url = website + "/wp-json/wc/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs;
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
PROBLEM
To improve security, I want to put consumer key and secret into the header, but I cannot get the following script to work
var url = website + "/wp-json/wc/v3/orders;
let authHeader = 'Basic ' + Utilities.base64Encode(ck + ':' + cs);
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
"headers": {"Authorization": authHeader},
};
var result = UrlFetchApp.fetch(url, options);
Current result = {"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
Expected result = JSON of orders
Is it an issue with my code? Or with WooCommerce API or Google Scripts?
There are a few issues with your code.
With UrlFetchApp.fetch() you need to use contentType instead of Content-Type.
However, in this case you don't even need to set it since application/x-www-form-urlencoded is the default. Same goes for the method property; it defaults to GET.
Moreover, if you want to err on the side of caution use Utilities.base64EncodeWebSafe(data, charset) to base64 encode your credentials instead of the non-web-safe version.
let url = website + "/wp-json/wc/v3/orders";
let encoded = Utilities.base64EncodeWebSafe(ck + ':' + cs, Utilities.Charset.UTF_8);
let options = {
"muteHttpExceptions":true,
"headers": {
"Authorization": "Basic " + encoded
}
};
let result = UrlFetchApp.fetch(url, options);
result = JSON.parse(result);

Angular 5 deleting a post on WP, REST API

I'm trying to delete a post using a delete request, but it seems I can't get the headers right.
project-list.component.ts
deleteProject(project) {
let headers: Headers = new Headers({
'Authorization': 'Bearer ' + this.token
});
this.projectsService.deleteProject(project.id, { headers: headers }).subscribe(
result => console.log(result),
err => console.error(err)
);
}
projects.service.ts
deleteProject(id: number, { headers: headers }): Observable<Project[]>{
return this.http.delete<Project[]>(this._wpBase + 'posts/' + id);
}
The DELETE request goes to the right URL, but it's Unauthorized. Under headers it says
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://.../wp-json/wp/v2/posts/69", ok: false, …}
My guess is it's because of the "headers: HttpHeaders", but I don't know how to fix it. Any help?
You are not passing headers to the delete request. Which you have created in your component.
This is how it should go.
deleteProject(id: number, { headers: headers }): Observable<Project[]>{
return this.http.delete<Project[]>(this._wpBase + 'posts/' + id, headers);
}
Update:
Your delete won't return Project object.
deleteProject(id: number, { headers: headers }): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}
Update 2:
Updated the parameter
deleteProject(id: number, headers: any): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}
Try using
deleteProject(id: number, headers: any): Observable<any>{
return this.http.delete(this._wpBase + 'posts/' + id, headers);
}

Angular 5 - HTTP post

I have a backend interface which I invoke with my Angular 1.3 application without problems. With my Angular 5 application I get an HTTP 403 (Forbidden)
I faced the request parameters in an picture (Angular 1.3 at the left side, Angular 5 at the right side):
My Angular 5 code looks like this:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
let options = new RequestOptions({ headers: headers });
return this.http.post(url, calendarEvent, options).map(res => res.json()).subscribe(res => console.log(res));
}
I have e.g. no idea why X-AUTH-TOKEN is not set with Angular 5 because I set it in the headers object with
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
and why OPTIONS is mentioned at Request Method with Angular 5 instead of POST like with angular 1.3.
Does anyone have any idea what I am doing wrong?
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url, calendarEvent, Options).map(res => res.json()).subscribe(res => console.log(res));
OPTIONS request is considered as a pre-flight request, which is sent before the actual request to check the existence of method.
If the request sent is a valid one, it will call the valid method.
And regarding the request header, you can use the one in the above answer.
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
For Angular5,
import { HttpClient, HttpHeaders } from '#angular/common/http';
const headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
By default, 'Content-Type': 'application/json'
Stop using map.
Subscribe the response and store it to Observable for further access.
Example:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
return this.http.post(url, calendarEvent, {headers: headers}).subscribe(res => console.log(res));
}

Parsing inbound emails from Sendgrid

I'm trying to parse incoming emails from the Sendgrid Inbound Webhook with Meteor, Picker and Body-Parser. I get the emails but when I log the request body I get an empty object. What am I missing here??
var bodyParser = require('body-parser');;
Picker.middleware( bodyParser.json() );
Picker.route('/incoming/', function(params, req, res, next) {
console.log("Body: " + JSON.stringify(req.body));
}
The problem was related to the content-type being multipart/form-data. Got it working like this:
var multiparty = require('multiparty');
var bodyParser = Npm.require('body-parser');
Picker.middleware(bodyParser.urlencoded({ extended: true }));
Picker.middleware(bodyParser.json());
Picker.route('/incoming/', function(params, req, res, next) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
console.log("Heureka: " + JSON.stringify(fields) + JSON.stringify(files));
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end("thanks");
});
});
I know this has already been answered but I've got an alternative solution using express and multer. I've created a repo express-sendgrid-inbound-parse to get you started.
I recommend leaving POST the raw, full MIME message unchecked as you can access to more email data.
console.log('dkim: ', body.dkim)
console.log('to: ', body.to)
console.log('cc: ', body.cc)
console.log('from: ', body.from)
console.log('subject: ', body.subject)
console.log('sender_ip: ', body.sender_ip)
console.log('spam_report: ', body.spam_report)
console.log('envelope: ', body.envelope)
console.log('charsets: ', body.charsets)
console.log('SPF: ', body.SPF)
console.log('spam_score: ', body.spam_score)
if (rawFullMimeMessageChecked) {
console.log('email: ', body.email)
} else {
console.log('headers: ', body.headers)
console.log('html: ', body.html)
console.log('text: ', body.text)
console.log('attachments: ', body.attachments)
console.log('attachment-info: ', body['attachment-info'])
console.log('content-ids: ', body['content-ids'])
}
It sounds like the incoming content from SendGrid doesn't have a application/json Content-Type, so bodyParser.json() can't parse it properly. Try adding a bodyParser.urlencoded() call as well, to try to parse a application/x-www-form-urlencoded Content-Type, to see if that helps. So something like:
var bodyParser = require('body-parser');
Picker.middleware(bodyParser.json());
Picker.middleware(bodyParser.urlencoded({ extended: false }));
Picker.route('/incoming/', function(params, req, res, next) {
console.log("Body: " + JSON.stringify(req.body));
}
You can also do this with multer. Here is the express server version:
const express = require(“express”);
const app = express();
var multer = require(“multer”);
var upload = multer();
app.post(“/”, upload.none(), function (req, res) {
console.log(req.body);
});

Resources