I'm trying use Wmata's metro gtfs apis but I'm not getting anything back. I tried using a fetch and also their own javascript example but I keep getting this type of response back.
I am able to get a response from their other feeds but just not any of the gtfs ones. When I try using postman I get a bunch of gibberish:
1495323752907:32:0020200213 *RED0ǃ��"9360(˅��"7993(����"3969(ш��"22094(����"3542(㋕�"2640(����"4387(͎��"4364( ����"5660(
I don't get what's going on.
const url =
"https://api.wmata.com/gtfs/rail-gtfs-static.zip?api_key=e13626d03d8e4c03ac07f95541b3091b";
let config = {
method: "GET",
mode: "no-cors"
};
fetch(url, config)
.then(res => console.log("res", res))
.catch(err => console.log("err", err));
Related
I am trying to get the URL of all the media inside of an organization post but all I can get is the image URN. I don't want to do another request to get the image but rather get the Posts information and the URL on the same call.
I tried to use the Posts API as the UGC Post API is currently marked as Legacy.
let testresp = await axios.get(https://api.linkedin.com/rest/posts?q=author&author=`urn%3Ali%3Aorganization%3A${LinkedInHelpers.URNtoID(orgsRes.data.elements[0].organizationalTarget)}`&fields=id,content:(media), {
headers: {
'Authorization': `Bearer ${accessToken.data.access_token}`,
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202301'
}
})
I also tried to use the ~ decorator to get extra data on the Media but it returns an empty object.
Hello please try making the get request add this address instead https://api.linkedin.com/v2/ugcPosts/${postId}
Try this :
axios.get(`https://api.linkedin.com/v2/ugcPosts/${postId}`, { headers })
.then((res) => {
const imgUrl = res.data.media_url;
console.log(imgUrl);
})
.catch((e) => {
console.error(e);
});
Context:
I'm building a app that can plot graph structures in electron with react. My backend is some Matlab code that can perform analysis on the graph struct. I'm using flask as the middle man communicating between them.
In the GUI i have a button that should be able to load the data that is provided in a excel file to the GUI. This should be done by a post request that uses a matlab script to load the data from the excel file and then returns this to javascript.
I have tried using something like this:
fetch('http://localhost:5000/getGriddata', {
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(fileObj.path)
}).then(response => response.json())
.then(data => setGriddata(data))
.catch(error => console.log(error));
The problem is that this code won't wait for the flask function to be finished. The flask function takes about 10 seconds depending on the graph size. Therefor i want to make this call in sync with my javascript code so that after the request, i can assure that the new griddata is defined.
Question:
Is there some way to ensure this when using fetch?
Do i need to find a different way of connecting to flask, if so what would that be?
Solution:
Instead of using the fetch api, another post brought me to the XMLHttpRequest. This works synchronously if the parameter is set to false.
With this my code looks like this:
var request = new XMLHttpRequest();
request.open("POST",'http://localhost:5000/getGriddata',false);
request.setRequestHeader('content-type', 'application/json');
request.send(JSON.stringify(fileObj.path));
console.log(request.response)
console.log(request.responseText)
setGriddata(JSON.parse(request.responseText))
Instead of using callbacks, try using async/await
const fetchGridData = async () => {
try {
const response = await fetch('http://localhost:5000/getGriddata', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(fileObj.path)
});
const result = await response.json();
setGriddata(result)
} catch(error) {
console.error("fetchGridData =>", error)
}
}
I am having some problems with trying to customize some code for Next-Auth, an authentication library for.Next.Js.
I want to be able to use Axios to manually make the post request rather than using a <form> element.
When I do the following, I have success.
<form method='POST' action='/api/auth/signout'>
<input name='csrfToken' value={csrfToken}/>
<button type='submit'>Submit</button>
</form>
But, when I try to do the same thing with axios, it doesn't work. I am attempting to call Next-auth's Signout endpoint, which I can do just fine using this html form element. I am expecting that the application with log the user out when calling this endpoint. When I do so with the form input, then it logs the user out. When calling the same endpoint with axios, it does not log the user out and instead nothing is happening
My axios request is
const submitForm = async () => {
if (csrfToken) {
const params = new URLSearchParams();
params.append("csrfToken", csrfToken);
try {
const response = await axios({
method: "POST",
url: "http://localhost:3000/api/auth/signout",
data: params,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}).then((res) => console.log(res));
} catch (err) {
console.log(err);
}
}
};
I have tried adding additional headers that I saw on the request that works properly, like:
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1"
I have tried making it multipart form data, passing it simply a body of {csrfToken}, and anything else I could think of.
Any tips or things that I might be overlooking?
I can't figure out why I am unable to make this work. I am using ANTD, rather than using regular html <form> elements throughout the application and would love to be able to use that additional functionality.
Edited:
I found the solution after a lot of headache. It turns out that everything was functioning as it should have previously, but Next-Auth has an issue with updating the client-side 'session' object when you make a manual change on the server side.
I fixed this by doing the following:
const res = await axios.post("/api/auth/signout", { csrfToken }).then(
async ({ request: { responseURL } }) =>
await router
.push(responseURL)
//this is from https://github.com/nextauthjs/next-auth/issues/596#issuecomment-943453568
//force the client side to refresh and revalidate since it doesn't want to do so on its own.
.then(() => document.dispatchEvent(new Event("visibilitychange")))
.catch((err) =>
console.log("err refreshing client side session ", err)
)
);
The trick that i was missing was the document.dispatchEvent(new Event('visibilitychange'). This is the magical piece that allows you to force the client side next-auth session to sync with cookies/db.
see here for more info https://github.com/nextauthjs/next-auth/issues/596#issuecomment-943453568
I can use the fetch API to do a HTTP POST request to an external JSON file, but it can't be done in the local JSON file.
class EasyHttp {
// http GET request
get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
// http POST request
post(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
}
const http = new EasyHttp();
const newData = {
customerID: 1252123,
name: "Aditya Padukhan",
purchase: "Realme alubhaja pro",
productID: "158-hb-122",
};
http
.post("customers.json", newData)
.then((res) => res.json().then((data) => console.log(data)))
.catch((err) => console.log(err));
And I got an error :
eassyhttp.js:16 POST http://127.0.0.1:5500/customers.json 405 (Method Not Allowed) (anonymous) # eassyhttp.js:16 post # eassyhttp.js:15 (anonymous) # app.js:16 app.js:18
SyntaxError: Unexpected end of JSON input at app.js:17
The specification says:
The POST method requests that the target resource process the
representation enclosed in the request according to the resource's
own specific semantics.
A static file has no means of processing the data that is posted. JSON isn't a programming language. There is nothing that can read the POST request and do anything with the data in it. Consequently, your web server is defaulting to saying "No, you can't POST here".
If you want to do something with the POST request, then you need to write some server side code that will do that something. (If you want to just overwrite the existing JSON then you should probably be using PUT instead of POST too). Note that allowing any HTTP request to change the data on the server is a bad idea and you really shouldn't allow it without some kind of authentication that limits requests to trusted people and/or logic to determine if the incoming data is "good".
I'm building out a project that is making a call to a blockchain API. Unfortunately, the data I'm getting back is circular so while it works in Postman my server errors when trying to convert it to JSON. I tried using JSON.stringify but nothing changed.
Here's the controller function:
blockchainController.search = (req, res) => {
axios({
method: 'GET',
url: `https://chain.api.btc.com/v3/address/${req.body.address}/tx`
})
.then(data => {
res.json({
message: 'Transactions loaded',
data: data
})
})
.catch(err => {
console.log(err);
res.send(err);
})
};
Any ideas for a workaround or a fix? I'd like to be able to send this data to my front-end but it ain't happening.
A solution could be to use a library designed to prune circular references.
I happen to have built such library: https://github.com/Canop/JSON.prune
You can simply call it with
let json = JSON.prune(yourCircularObject);
This adds some "-pruned-" marks whenever a reference is ignored.
If you prefer a "silent" removal, you can do
let json = JSON.prune(yourCircularObject, {prunedString: undefined });