I am very new to NodeJS and would request the readers to please be kind if my query is too basic.
I have an xml file that was easy to parse and target certain nodes with DOMParser and querySelector with javascript for the frontend (browser)... but I was trying the same on the backed with node and I realised that DOMParser is not really a part of the backend.. Here's what I am trying..
fetch(`http://localhost:3000/data/rogan/gallery.xml`)
.then((response) => response.text())
.then((xml) => {
const xmlDOM = new JSDOM(xml, {
contentType: "text/xml",
features: {
QuerySelector: true,
},
});
const images = xmlDOM.querySelector("img");
console.log(images);
res.send(images);
})
.catch((err) => console.log(err));
});
Is the use of querySelector wrong in node? I mean is that a front-end thing and not something we use in node?
I am able to get the XML but I am not sure how to target some specific nodes in the xml that I want to push to an array or an object (I haven't yet reached that stage but first I need to target the nodes)..
Any help/advise would be appreciated.
It looks like you call the querySelector in the wrong way. Here is what I found on the documentation of JSdom:
dom.window.document.querySelector("p").textContent
In your case, I should be
xmlDOM.window.document.querySelector("img");
Related
I'm going to use the following code as an example to frame my question. It's basically just the code required to pull a list of to dos from an SQLite3 database:
So, there's an axios request in the front end:
useEffect(() => {
axios.get('http://localhost:3001/todo', {})
.then(res => {
setTodoList(res.data)
})
.catch(err => {
console.log(err)
})
}, [])
...which links to the following function in the back end:
server.get('/todo', (req,res) => {
// res.json(testData)
const todos = db('todos') //this is shorthand for 'return everything from the table 'todos''
.then(todos => {
return res.json(todos)
})
})
..the data from this GET request is then rendered within a react component, as a list of text.
I'm just confused about the flow of data - when is it HTTP, when is it JSON, what form does the data come out of the database as, and how is it that these different protocol/languages can talk to each other?
I get the overall principle of a GET request and async functions, I just don't get what's going on under the hood. Thanks!
That's a lot of questions about basic issues. But here are some answers. Firstly, you can simplify the server function as:
server.get('/todo', (req, res) => {
db('todos').then(todos => res.json(todos));
});
The data from the db is a Javascript array by the time you are dealing with it in Express. res.json converts it into JSON, which is of course, just a string.
Express creates an HTTP response, which consists of some headers (key value pairs such as Content-Length: and so on) followed by a body, which in your case is just a JSON blob, a string. That response object is sent over the network via HTTP.
The browser receives the response and axios is kind enough to handle the grunt work of reading the headers and turning your JSON back into a Javascript array/object which can then be handled inside React.
The part I can't answer is "how is it that these different protocol/languages can talk to each other", because that is very complex and the question is not well defined. There are many network layers involved.
I am trying to get a JSON from
https://api.nal.usda.gov/fdc/v1/foods/search?api_key=DEMO_KEY&query=ketchup
and do something with it by storing it into a variable. I used Node and Express in my work. Can anyone please tell me how to.
Very much appreciated, Thanks.
I asume that your server is working and fetching data correctly.
Then you can use something like that:
async function getData() {
return fetch('https://api.nal.usda.gov/fdc/v1/foods/search?api_key=DEMO_KEY&query=ketchup')
.then(response => response.json())
}
getData()
.then(data => console.log(data))
Like zinkn say here
I am trying implement REST API using REACT AND NODE. How to get JSON from front end(REACT JS)drag and drop images in template ex."https://www.canva.com/templates/" to store JSON in Mongodb using NODE JS.
Thanks in advance
You can use fetch api to call a particular route and send data along with it to nodejs backend.
You just need to do simply like this:
async function sendData(){
let res = await fetch(url, {
method: 'POST',
mode: 'CORS',
body: {}, //the json object you want to send
headers: {}, //if required
}
)
}
Hope this helps!
Since you asked how to send JSON to node.js I'm assuming you do not yet have an API that your front end can use.
To send data to the back end you need to create an API that accepts data.
You can do this quickly and easily using express.js.
Once the server is running and it has an endpoint to send data to, you can create a request (e.g. when sending data it should be a POST request).
This can be done in many different ways, although I would suggest trying axios.
Hope this helped.
Check the example to get the Json value and update it.
axios.get('https://jsonplaceholder.typicode.com/todos/'+ this.props.id + '/')
.then((res) => {
this.setState({
// do some action
});
})
.catch(function (error) {
console.log(error);
});
My requirement is to generate pdf view of UI(angular 4 app) using Nodejs api. For that i fetched the entire content from UI and did some pre-processing which will be send to nodejs api. In node api i used html-pdfpackage to generate pdf from the html received. Am able to generate pdf with proper styling as it appears in UI. Below are my questions
What is the safe way to pass the entire UI content(html, styles, bootstrap css) to Node api. (Currently passing as normal string for POC purpose)
How will i return the pdf stream generated by html-pdfpackage back to UI to show it on new tab
html-pdf package
Node api call from angular:
this.http.post('http://localhost:3000/api/createpdf', { 'arraybuff': data }, options)
.catch(this.handleError)
.subscribe(res => {
})
Currently data is normal html string, which i am retrieving by setting body-parser in node.
I don't think there is any better way to pass HTML to server or may be I am not aware of it, but to open the link in new tab use below code
this.http.post('http://localhost:3000/api/createpdf', { 'arraybuff': data }, options)
.catch(this.handleError)
.subscribe(res => {
var blob = new Blob([(<any>res)], { type: 'application/pdf' });
var url = window.URL.createObjectURL(blob);
window.open(url);
})
I worked on a project with Spring Boot java framework where guys automated API docs generation. Every time you run BDD/Integration style tests, there was api blue print file created out from mocha tests. Then it ran generate-html-from-api blueprint. I liked this approach as it has two advantages:
1) API docs are always correct and up-to-date
2) saves time, because no need to write another documentation file (like apidoc).
Has anyone tried and has working example for node projects? I found api-doc-test plugin, however its documentation is limited. ? Ideally, I would like just to run:
mocha --recursive
Which would generate api-doc.html and place under test/tmp/.
I have looked at swagger but I really don't want to specify endpoint information twice and it would really be awesome just write once in BDD tests and have double result (tests + docs) at the same time.
https://github.com/stackia/test2doc.js
I'm working on this project, which enables generating documents (currently only API blueprint) from BDD tests, just exactly what you need.
Test code example:
const doc = require('test2doc')
const request = require('supertest') // We use supertest as the HTTP request library
require('should') // and use should as the assertion library
// For Koa, you should exports app.listen() or app.callback() in your app entry
const app = require('./my-express-app.js')
after(function () {
doc.emit('api-documentation.apib')
})
doc.group('Products').is(doc => {
describe('#Products', function () {
doc.action('Get all products').is(doc => {
it('should get all products', function () {
// Write specs towards your API endpoint as you would normally do
// Just decorate with some utility methods
return request(app)
.get(doc.get('/products'))
.query(doc.query({
minPrice: doc.val(10, 'Only products of which price >= this value should be returned')
}))
.expect(200)
.then(res => {
body = doc.resBody(res.body)
body.desc('List of all products')
.should.not.be.empty()
body[0].should.have.properties('id', 'name', 'price')
body[0].price.desc('Price of this product').should.be.a.Number
})
})
})
})
})