How to keep line breaks in POST message - javascript

When i get the content of an email it is formatted with line breaks but when i send it to the API the result is text with no white space.
Is there any way to keep the spacing?
Edit:
const postNewTask = (taskTitle, taskComment, workerId) => {
const { projectId, tasklistId } = dataStore();
const { userEmail, apiKey } = credentialsStore();
const options = {
method: 'POST',
headers: {
Authorization:
'Basic ' + Utilities.base64Encode(`${userEmail}:${apiKey}`),
},
};
if (taskComment && workerId) {
options.payload = JSON.stringify({
name: taskTitle,
comment: {
content: taskComment,
},
worker: parseInt(workerId),
});
}

I solved it. I just had to use taskComment.replace(/(?:\r\n|\r|\n)/g, '<br>') and the API knew what to do from there.
Final working code:
const postNewTask = (taskTitle, taskComment, workerId) => {
const { projectId, tasklistId } = dataStore();
const { userEmail, apiKey } = credentialsStore();
const options = {
method: 'POST',
headers: {
Authorization:
'Basic ' + Utilities.base64Encode(`${userEmail}:${apiKey}`),
},
};
if (taskComment && workerId) {
options.payload = JSON.stringify({
name: taskTitle,
comment: {
content: taskComment.replace(/(?:\r\n|\r|\n)/g, '<br>'),
},
worker: parseInt(workerId),
});

Related

Why I can get and api data with fetch and not with axios?

I got this test code:
import axios from 'axios';
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json"},
withCredentials: true
};
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
const readWithFetch = (basicAuth) => {
return new Promise(res=>{
let headers = new Headers();
headers.set('Authorization', basicAuth);
fetch('https://geolite.info/geoip/v2.1/country/me?pretty', {
method: 'GET',
headers: headers,
}).then(response => res(response.json()));
})
}
const readData = async () => {
let user = '<my_api_user>';
let passwd = '<my_api_key>';
let basicAuth = 'Basic ' + Buffer.from(user + ":" + passwd).toString('base64');
let geoData;
//geoData = await readWithFetch(basicAuth);
geoData = await readWithAxios(basicAuth, user, passwd);
console.log(geoData);
}
readData();
I'm trying to understand why readWithFetch works fine and axios gets connection refused. It's a simple basic auth... nothing fancy.
I've tried all these readWithAxios versions:
version 1
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json"},
withCredentials: true
};
console.log('options', options);
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
version 2
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
console.log('options', options);
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
version 3
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
method: 'GET',
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
version 4
return axios(options);
}
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
method: 'GET',
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
return axios(options);
}
What is the correct way to write readWithAxios ?
You have a triple slash in https:///geolite in the Axios versions. It should be https://

Cannot set property 'status' of undefined

My script is running well but at the end I get an error message Error during script execution.
Cannot set property 'status' of undefined.
Does anybody have a clue what I am doing wrong here?
const fs = require("fs-promise");
const axios = require("axios");
const jsonxml = require("jsonxml");
const tmp = require("tmp");
module.exports = {
mpGetChecklist: async function (mpurl, bearer, systemGetChecklistMethod, systemGetChecklistId, systemGetChecklistDatasetName) {
var getChecklist = {
method: systemGetChecklistMethod,
url: mpurl + "/connector/system/getChecklist?id=" + systemGetChecklistId,
headers: {
Authorization: "Bearer " + bearer,
},
};
let tmpPath = tmp.fileSync({ postfix: ".xml" });
let result;
await axios(getChecklist)
.then(function (response) {
console.log(JSON.stringify(response.data));
let xmlOptions = { header: true, root: "JSON", indent: true };
let xmlString = jsonxml(response.data, xmlOptions);
try {
fs.writeFileSync(tmpPath.name, xmlString);
result = { status: "succes", xmlPath: tmpPath.name, datasetName: systemGetChecklistDatasetName };
} catch (error) {
result = { status: "error", msg: error };
}
})
.catch(function (error) {
console.log(error);
});
return result;
},
};

Request_BadRequest in O365

I am trying to send a email with the help of O365. I have configured everything but I am getting a error
GraphError { statusCode: 405, code: 'Request_BadRequest',
message: 'Specified HTTP method is not allowed for the request
target.', requestId: '34f321-57de-4483-b97d-5957f8786ecb', date:
2019-09-16T00:17:53.000Z, body:
'{"code":"Request_BadRequest","message":"Specified HTTP method is not
allowed for the request
target.","innerError":{"request-id":"34f803b1-57de-4483-b97d-5957f8786ecb","date":"2019-09-16T05:47:51"}}'
}
Code
const APP_ID = "XXXXXXXXXXXXXXXXXX";
const APP_SECERET = "XXXXXXXXXXXXXX";
const TENANT_ID = "XXXXXXXXXXXXXXXX";
const TOKEN_ENDPOINT = "https://login.microsoftonline.com/XXXXXXXXXXXXXXXXXXXXX/oauth2/v2.0/token";
const MS_GRAPH_SCOPE = "https://graph.microsoft.com/.default";
const GRANT_TYPE = "client_credentials";
const graphScopes = ["User.Read", "Mail.Send"]; // An array of graph scopes
const request = require("request");
const endpoint = TOKEN_ENDPOINT;
const requestParams = {
grant_type: GRANT_TYPE,
client_id: APP_ID,
client_secret: APP_SECERET,
scope: MS_GRAPH_SCOPE
};
request.post({
url: endpoint,
form: requestParams
}, function(err, response, body) {
if (err) {
console.log("error");
} else {
// console.log(response);
// console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
console.log("Access Token=" + parsedBody.access_token);
// testGraphAPI(parsedBody.access_token);
let accessToken = parsedBody.access_token;
getMe(accessToken);
}
}
});
function getMe(accessToken) {
require("isomorphic-fetch");
const fs = require("fs");
const MicrosoftGraph = require("#microsoft/microsoft-graph-client").Client;
const options = {
defaultVersion: "v1.0",
debugLogging: true,
authProvider: (done) => {
done(null, accessToken);
},
};
// https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/samples/node/main.js
// https://learn.microsoft.com/en-us/graph/overview
const client = MicrosoftGraph.init(options);
// send an email
const sendMail = {
message: {
subject: "Test o365 api from node",
body: {
contentType: "Text",
content: "Testing api."
},
toRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}],
ccRecipients: [{
emailAddress: {
address: "test#abc.com"
}
}]
},
saveToSentItems: "false"
};
client.api('/users/test1#abc.onmicrosoft.com ').post(sendMail).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
}
Can someone tell me where I am going wrong. Please help me out
I had the same error and it was a malformed url when sending to the users.
I think your url should be /users/test1#abc.onmicrosoft.com/sendMail

Access the `access_token` property in localstorage

I have saved the token in localstorage: localStorage.setItem ('token', JSON.stringify (res.data)). I am trying to access the access_token property.
JSON.parse(localStorage.getItem(token['access_token']))
It gets error: token is undefined;
getToken = () => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const url = '/oauth2/token';
axios({
method: 'post',
url,
data,
config
})
.then(res => {
if (res.status === 200) {
localStorage.setItem('token', JSON.stringify(res.data))
this.setState({
token: res.data
})
} else {
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.error(err);
alert('error');
});
}
You syntax needs to be corrected to as below
JSON.parse(localStorage.getItem('token'))['access_token']
You can use
var tokenData = JSON.parse(localStorage.getItem('token'));
console.log(tokenData.access_token);
Example how to store object in localStorage
var myObj = {
one: {
title: 'first',
id: 1,
customKey : {
first: "first",
second: "second"
}
},
two: {
title: 'second',
id: 2
},
three: {
title: 'this is the third',
id: 3
}
};
localStorage.setItem('storeObj', JSON.stringify(myObj));
var getObject = JSON.parse(localStorage.getItem('storeObj'));

function based on other callBack function... react-native

when user wants to to POST somthing he must be singed in(without username & pass).
Problem is i'm trying to make when CreatePost() invoked it will call SingUser() and based on SingUser() fetch request it will call CreatePost() again to let user post after he sign in.
this is in createpost component
CreatePost(){
fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)
}).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status =='inactive'){
//SignUser
}else{
//post
}
}).catch((error)=>{ //later
});
}
here is SingUser() in other file
async function SignUser() {
try{
User.vtoken = await AsyncStorage.getItem('vtoken');
var userTemp={
vtoken: User.vtoken,
ntoken : User.ntoken
}
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=> response.json()).
then((responseJson)=>{
if(responseJson.path == 2){
Save(responseJson, userTemp);}
else return;
}).catch((error)=>{
});
}catch(error){}
}
async function Save(result , userTemp){
try{
await AsyncStorage.setItem('vtoken', result.vtoken);
User.vtoken = result.vtoken;
userTemp.vtoken = result.vtoken;
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=>response.json()).
then((responseJson)=>{
return 'done';
}).catch((error)=>{})
}
catch(error){}
}
export {SignUser}
i hope u understand what im trying to do if there is better way to do it thnx:(
You can do something like this:
const errorCodeMap = {
USER_INACTIVE: 10,
}
const statusMap = {
INACTIVE: `inactive`
}
const METHOD = `POST`
const APPLICATION_JSON = `application/json`
const headerDefault = {
Accept: APPLICATION_JSON,
'Content-Type': APPLICATION_JSON,
}
const who = `post`
async function createPost(payload, options) {
try {
const {
url = ``,
fetchOptions = {
method: METHOD,
headers: headerDefault,
},
} = options
const {
post,
} = payload
const response = await fetch(url, {
...fetchOptions,
body: JSON.stringify(post)
})
const {
status,
someUsefulData,
} = await response.json()
if (status === statusMap.INACTIVE) {
return {
data: null,
errors: [{
type: who,
code: errorCodeMap.USER_INACTIVE,
message: `User inactive`
}]
}
} else {
const data = someNormalizeFunction(someUsefulData)
return {
data,
errors: [],
}
}
} catch (err) {
}
}
async function createPostRepeatOnInactive(payload, options) {
try {
const {
repeat = 1,
} = options
let index = repeat
while (index--) {
const { data, errors } = createPost(payload, options)
if (errors.length) {
await signUser()
} else {
return {
data,
errors,
}
}
}
} catch (err) {
}
}
solve it, I did little adjustments
async CreatePost(){
try{
var response = await fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)});
var responseJson = await response.json();
if(responseJson.status =='inactive' && postRepeat == true){
postRepeat == false;
await SignUser();
this.CreatePost();
}
else{
//posted
}
}catch(err){}
}

Categories