# Examples
# Node.js
The following example will get 2 Blog Posts from the Bucket Simple React Blog.
- Install
axios
(opens new window)
npm install axios
- Add the following code to a file titled
index.js
// index.js
const axios = require('axios')
axios.post('https://graphql.cosmicjs.com/v2', {
query: `{
getObjects(
bucket_slug: "simple-react-blog",
input: { type: "posts", limit: 2 }
){
objects {
title
}
total
}
}`
})
.then(function (response) {
const objects = response.data.data.getObjects
console.log(objects)
})
.catch(function (error) {
console.log(error)
});
- Run the following command
node index.js
# Apollo
You can use Apollo Client (opens new window) to connect to the Cosmic GraphQL API. You will need to use a browser build system as noted on the Apollo Client README (opens new window).
- Install Apollo packages
npm install apollo-boost graphql
- Create a file titled
index.js
and add the following example code:
// index.js
import ApolloClient from "apollo-boost";
const client = new ApolloClient({
uri: "https://graphql.cosmicjs.com/v2"
});
import { gql } from "apollo-boost";
client
.query({
query: gql`
{
getObjects(
bucket_slug: "simple-react-blog",
input: { type: "posts", limit: 2 }
){
objects {
title
content
}
total
}
}
`
})
.then(result => {
console.log(result)
document.getElementById('root').innerHTML = JSON.stringify(result.data.getObjects);
});
- Install
webpack-cli
(opens new window)
npm i -g webpack-cli
- Create a file titled
webpack.config.js
// webpack.config.js
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
- Create an HTML file titled
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cosmic GraphQL Apollo Example</title>
</head>
<body>
<div id="root"></div>
<script src="dist/bundle.js"></script>
</body>
</html>
- Run webpack
webpack
- View the
index.html
file in a browser.
# Ajax
Get one Object using client-side AJAX method.