Trouble importing json file - tabulator

I am trying to use public json file as data source with following javascript:
const url = "https://data.melbourne.vic.gov.au/resource/ez6b-syvw.json";
var table = new Tabulator("#example-table", {
ajaxConfig:{
method: 'GET'
},
ajaxURL: url, //ajax URL
index:"MessageID",
autoResize:true,
layout:"fitData", //layout options
placeholder:"Awaiting Data...",
columns:[ //Define Table Columns
{title:"timestamp", field:"timestamp"},
{title:"temperature", field:"temp_avg"},
{title:"humidity", field:"humidity_avg"},
{title:"latitude", field:"latitude"},
{title:"longtitude", field:"longtitude"},
],
ajaxResponse:function(url, params, response){
//url - the URL of the request
//params - the parameters passed with the request
//response - the JSON object returned in the body of the response.
return response; //pass the data array into Tabulator
},
rowClick:function(e, row){ //trigger an alert message when the row is clicked
alert("Row " + row.getData().MessageId + " Clicked!!!!");
},
});
But I get following console message in chrome:
Access to fetch at 'https://data.melbourne.vic.gov.au/resource/ez6b-syvw.json' from origin 'http://192.168.0.6' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
data.melbourne.vic.gov.au/resource/ez6b-syvw.json:1 Failed to load resource: net::ERR_FAILED
tabulator.min.js:5 Ajax Load Error - Connection Error: TypeError: Failed to fetch
(anonymous) # tabulator.min.js:5
tabulator.min.js:5 Ajax Load Error: TypeError: Failed to fetch
I donot know what am I doing wrong?
Please help.
Thanks.

It looks like there is an issue getting the data from your resource. Tabulator appears to always send an Access-Control-Allow-Origin, but your resource does not allow this. So, a workaround is to use your own fetch request instead of the Tabulator ajax options. Then you can use setData on the table instance.
Here is an example. https://jsfiddle.net/nrayburn/8wd3zo9q/33/
I am not sure if this is a bug, or if I am just not seeing a way to do it.

Add this in your ajaxConfig and you are good to go.
ajaxConfig:{
mode: "no-cors",
method: 'GET'
}

Related

TypeError: Converting circular structure to JSON when axios response is forwarded

I have an API where I need to call another API inside the controller function. Which I do using Axios, but when I try to attach Axios's response on my original API's response, it throws this error:
TypeError: Converting circular structure to JSON.
Here's a sample code snippet
const userController = async (req,res)=>{
const ax = await axios.put(someURL, reqBody)
res.status(200).json(ax)
}
I know it's nonsensical to do something like this and I know why this error is caused but could somebody explain to me How it's happening in this case?
TypeError: Converting circular structure to JSON is when some property in the object is repeated in another inner object.
Axios response has these properties:
// `data` is the response that was provided by the server
data: {..your real json response..},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
request: {}
If you send the entire axios response object to be converted to json, some property in your real json response could repeat the name of private axios properties like: status, data config, etc
Fix
Try with ax.data instead use the entire axios response ax

How to log the actual request header when using fetch API

Beginner question, I am using the fetch API in one of my Cloudflare Service Worker to send request to a third party; Everything works fine that I am able to send out the request and receive response; But now I have a need to log everything I sent and received, which I am not sure how exactly can I do so;
The main requirement:
Able to log the whole request header being sent
The problem is that the request header that I specified is not the full header being sent, like in the following example I only specified the content-type, but in real practice it will send with more properties added by the application itself, e.g. accept, x-forwarded-for, content-length, etc.
Request:
var toThirdPartyReqMethod = 'POST';
var toThirdPartyReqHeader = {'content-type': 'application/json'};
var toThirdPartyReqSetting = {
method: toThirdPartyReqMethod,
headers: toThirdPartyReqHeader,
body: toThirdPartyReqBodyArrayBuffer
};
var toThirdPartyUrl = "https://somewhere.com";
var fromThirdPartyResponse = await fetch(toThirdPartyUrl, toThirdPartyReqSetting)
var fromThirdPartyResponseBodyArrayBuffer = await fromThirdPartyResponse.arrayBuffer();
I am able to use fromThirdPartyResponse to digest the response; but I have no idea how to record the exact request I sent out.
I tried to do it as follows:
var oriReqHeaderContentType = fromThirdPartyResponse.request.headers.get("content-type");
But obviously it is not the right answer and returned with the following error:
TypeError: Cannot read property 'headers' of undefined
Anyone gets some idea of how to log the request being sent when using fetch API?
Sorry for asking beginner questions :(
You can access request headers like this
const contentType = req.get("Content-Type");

getting 403 error while sending file to githib via REST using nodejs

I want to send multiple files to Github repository via nodejs. Tried several approaches and end up using node-rest-client module. Tried below code send a sample file to repository called 'metadata'. But after post I am getting error message "Request forbidden by administrative rules. Please make sure your request has a User-Agent header"...please let me know if anyone faced this error before and get rid of it.
convertval = "somedata";
var dataObj = {
"message": "my commit message",
"committer": {
"name": "Scott Chacon",
"email": "ravindra.devagiri#gmail.com"
},
"content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}
debugger;
var Client = require('node-rest-client').Client;
var client = new Client()
var args = {
data: dataObj,
headers: { 'Content-Type': 'application/json' },
};
client.post("https://api.github.com/repos/metadata/contents", args, function (data, response) {
console.log("file send: True : " + data);
});
According to the REST API:
All API requests MUST include a valid User-Agent header. Requests with
no User-Agent header will be rejected.
First of all, you need to define 'User-Agent' with value 'request' in your request header. Refer to this link.
Second, endpoint you are trying to call might require authentication. Generate a personal token from here, add that token in your request header, 'Authorization': 'token '.
If you're using Git extensively in your code, I suggest you to use this - Nodegit.
Edit:
I don't think sending multiple files in a single request is possible in 'Contents' endpoints group (link).
You can checkout Git Data API (as discussed here).

NetSuite: How to make http request sending cookies?

I need to call an external API to get some data from a SuiteScript file and I'm getting an issue. The GET call needs to go with credentials (basically, it has to go with the cookies in the Request Header).
If I make the API call from the chrome console setting withCredentials = true, but when I make that API call with NetSuite N/https module -through https.get()- the cookies don't go on the request header.
So in summary, I'm looking for a way to set withCredentials = true on the http.get() call or to be able to somehow get the cookies from my SuiteScript so that I can manually set it in the header option of the call.
Thanks in advance for your time!
Within the get, pass the headers option and populate your header values. I believe these are KVP.
If your external app is expecting information about the logged in user then what you probably want to do is an XHR request (jQuery's $.getJSON would be your best bet). If you need to pass information to a server side script then you'd call your Suitelet with the returned data.
A post example would be as follows. Note the withCredentials :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
dataType: "json",
data: jsonData,
xhrFields: {
withCredentials: true
},
success: function(response){
console.log(response);
},
error: function(response){
console.log('error: ' + JSON.stringify(response));
}
});

Ajax POST to Node.js through Nginx not getting correct response

I'm trying to send an ajax post request to a node.js microservice through nginx. The requuest is as follows:
$.post('http://localhost:80/api/signup', formData, function( data, status) {
console.log(JSON.stringify(data));
console.log(JSON.stringify(status));
}).done(function(data, status) {
alert( "second success" );
console.log(JSON.stringify(data));
console.log(JSON.stringify(status));
})
.fail(function(data, status) {
console.log('error');
console.log(JSON.stringify(data));
console.log(JSON.stringify(status));
})
.always(function(data, status) {
console.log(JSON.stringify(data));
console.log(JSON.stringify(status));
console.log('fiished');
});
The request reaches the microservice. But the response is as follows (which is always the error function):
"data" is always:
{"readyState":0,"status":0,"statusText":"error"}
And the "status" is always:
error
which is not the expected response at success nor failure.
How can I fix this?
Moreover, "formData" parameters appear as queries on the url once submitted. How can I stop that?
Update*
I have also tried adding event.preventDefault(); but now it gives me the following:
XMLHttpRequest cannot load http://localhost:3000/api/signup. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
{"readyState":0,"status":0,"statusText":"error"}
I have also tried:
$.ajax({
type: "POST",
url: "http://localhost:3000/api/signup",
data: JSON.stringify(formData),
success: function(dataString) {
console.log(JSON.stringify(dataString));
}, error: function(error) {
console.log(JSON.stringify(error));
}
});
But got the same No 'Access-Control-Allow-Origin' header is present on the requested resource as above.
Update
There is a valid and possibly more detailed answer on "No 'Access-Control-Allow-Origin' header is present on the requested resource". However, I find the answer I accepted here more direct and clear.
Are you executing the ajax request from the browser or localhost? If you are executing it from your browser it may be CORS issue. If you want to be able to execute that ajax request from your browser you should modify your server configuration/code to allow cross-origin HTTP requests.
This looks similar to your issue. CORS issue in Jquery Ajax Post

Resources