I have this array and need to pass all the variables inside the request url.
I've tried as result.variable1, result['variable1'], result[0], but nothing works.
How can access each variable inside the array and pass to url?
result.push({variable1: string1, variable2: string2});
request.post({
url: "mydomain.com/text="Hi"+result[variable1]+"\\n"+result[variable2]+"Hello!",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
form: {
myfield: "myfieldvalue"
}
}, function (response, err, body){
console.log('Body:',JSON.parse(body));
}.bind(this));
result.push({variable1: string1, variable2: string2});
This will result in the array becoming as
result = [{variable1: string1, variable2: string2}].
So if you want 'variable1', you need to access it as result[0].variable1.
Related
I have tried many different ways but to no avail
API Spec - https://developers.facebook.com/docs/graph-api/reference/page/videos/
Param - content_tags ( list ) --> is what required
Below is my form data that is being posted
const formData = {
file_url: postOptions.filepath,
title: postOptions.title,
description: postOptions.description,
content_tags: ['tags', 'hello', 'hi']
};
HTTP Request Options
const options = {
url: https://graph-video.facebook.com/v9.0/${pageId}/videos?access_token=${accessToken},
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
formData,
};
Error response returned.
{"error":
{
"message":"(#100) Param content_tags[0] must be a valid ID string (e.g., \"123\")",
"type":"OAuthException",
"code":100,
"fbtrace_id":"ANoCbTSnh4uL960SjyE6XBV"
}
}
As per documentation, seems it has to be not just any string but NUMBER string which are predefined IDs of the tag list<numeric string>
From documentation
Tags that describe the contents of the video. Use search endpoint with type=adinterest to get possible IDs.
Example:
~~~~
/search?type=adinterest&q=couscous
~~~~
Here's full path of the above example shown by facebook, how you can get some IDs:
https://graph.facebook.com/search?type=adinterest&q="home"&limit =10&access_token={{access_token}}
I am having trouble sending JSON data that contains special characters like ` to my Node Express server.
I posted How can I render UTF-8 characters in JSX without using dangerouslySetInnerHTML in 2020 earlier, but I think I am approaching the problem incorrectly.
The Problem:
When I submit my JSON form data using an HTTP Client, my req.body HTMLifies special characters:
// Sending a nested JSON.stringified Object
const response1 = await fetch(
`${baseUrl}/chhands/${granthState.lastChhand.id}/pauris`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pauri: formattedTuk,
last_pauri_id: granthState.lastPauri?.id,
}),
}
);
Here is a result of the console.logging {pauri: formattedTuk, last_pauri_id: granthState.lastPauri?.id}:
What it looks like on the backend when I submit the nested JSON object:
Here is where the where I am even MORE confused:
Here, instead of sending a nested object, I only send the formattedTuk [Array] object, which looks like:
[
{
line_number: 1,
content_unicode: 'ਆਪ ਅਛਤ ਸਮਰੱਥ ਪ੍ਰਭੁ ਦਈ ਬਡਾਈ ਨਾਮ ।',
content_gs: 'Awp ACq smr`Q pRBu deI bfweI nwm [',
content_transliteration_english:
"aap achhat samara'th prabh dhiee baddaiee naam |",
first_letters: 'ਆਅਸਪਦਬਨ',
thamkis: [],
vishraams: [],
},
];
// Sending the raw array object stringified {}
const response2 = await fetch(
`${baseUrl}/chhands/${granthState.lastChhand.id}/pauris`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formattedTuk),
}
);
What it looks like on the backend when I submit the ONLY the Array Object:
Other things I've tried:
Used Axios (instead node-fetch) and it gave the same effect
Used POSTMAN and it had the same effect
Double checked my Content-Type and charset but it all looks good.
Here is my Express middleware settings. I was using body-parser before, but it seems that express.json() is giving me the same effect. I've also seen people recommend using qs.stringify() but what I am doing seems fairly simple.
app.use(morgan('tiny'));
app.use(helmet());
app.use(express.json());
app.use(cors());
Updates:
Here is the exact "Copy as Fetch" value:
fetch("http://localhost:1469/api/v1/chhands/53/pauris", {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"referrer": "http://localhost:3000/",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "{\"pauri\":[{\"line_number\":1,\"content_unicode\":\"ਆਪ ਅਛਤ ਸਮਰੱਥ ਪ੍ਰਭੁ ਦਈ ਬਡਾਈ ਨਾਮ ।\",\"content_gs\":\"Awp ACq smr`Q pRBu deI bfweI nwm [\",\"content_transliteration_english\":\"aap achhat samara'th prabh dhiee baddaiee naam |\",\"first_letters\":\"ਆਅਸਪਦਬਨ\",\"thamkis\":[],\"vishraams\":[]}],\"last_pauri_id\":60}",
"method": "POST",
"mode": "cors",
"credentials": "omit"
});
I would like to a check for max-age so I remove items from cache when they get old, but I can't get my own header back for some reason.
export function cacheResponse(url, response) {
caches.open('my-cache').then(function(cache) {
cache.put(url, new Response(JSON.stringify(response), {
headers: {
'Cache-Control': 'max-age=1',
'Content-Type': 'application/json;charset=UTF-8'
}
}));
});
}
cacheResponse('/hello', {hello: "world"})
I can see this working in the Application tab in chrome and I can see those 2 headers in the preview, but when I pull the item back out the headers object is null.
cache.match(url).then(async function(object) {
console.log(object.headers) // null
var body = await object.clone().json(); // {hello: "world"}
})
The object looks like this
object: Response
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: ""
type: "default"
url: ""
Seems like I should be able to lookup the headers from calling match() no?
That should work; you should be able to call response.headers.get('cache-control') to retrieve the value (assuming this is a same-origin response).
Here's a snippet of code that I just tested which worked when run in the JS console:
async function test() {
const constructedResponse = new Response('test', {
headers: {'cache-control': 'max-age=1'}
});
const cache = await caches.open('test');
cache.put('/test', constructedResponse);
const matchedResponse = await cache.match('/test');
console.log(`cache-control: ${matchedResponse.headers.get('cache-control')}`);
}
I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.
Example:
I'm calling app.get("/wp/page/create/:id", function(req, res)
Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.
I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.
Code:
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
res.send(data).end()
console.log("All done!");
})
})
When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.
If I restart the server it works the again on the first attempt but fails on the second/third.
Any idea what I am doing wrong?
I have resolved the issues. The simple solution was to clear the headers containing the variable.
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
postHeaders['If-Match'] = "";
res.send(data).end()
console.log("All done!");
})
})
postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .
Try this instead of the first line
var postHeaders = Object.assign({}, headers);
Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.
I have a call made from my client that passes in some post data like this:
function doSomethingApi(email) {
return axios({
method: 'post',
url: `/api`,
data: {
scan_refference: 'ref',
user_email: email
}
})
}
On the server side this gets proxied to apply certain secrets:
app.post('/api', (req, res) => {
const url = 'https://my.api.com';
req.pipe(request({
url,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
auth: {
user: secrets.USERNAME,
pass: secrets.PASSWORD
},
body: {
value1: `${secrets.VALUE1}`,
value2: `${secrets.VALUE2}`
}
})).pipe(res);
});
request and axios are just 2 different http libraries I use, one is preferred for client other for server, thats all. Issue now is that I am overwriting body in my proxy, where as I want to simply add value1 and value2 to existing body passed from client.
First get the body from the initial call as a JSON object. This depends on what you use, but e.g. in Express you could:
app.use(express.bodyParser());
Then
var previousBody = req.body
Finally merge the initial JSON with whatever you want (NOTE: this means your client will definitely not be able to use the "value1" and "value2" properties, because they will be overwritten)
body: Object.assign(previousBody, {
value1: `${secrets.VALUE1}`,
value2: `${secrets.VALUE2}`
})