i already have try to install mongodb via npm but i keep getting error Cannot find module "fs"
and my code is look like this
<script>
const MongoClient = require('mongodb').MongoClient;
export default {
data(){
return{
msg:'this is a test'
}
},
created:function(){
MongoClient.connect('mongodb://127.0.0.1:27017', (err, database) => {
if (err){
console.log('1');
}else{
console.log('2');
}
})
}
}
</script>
<template>
<div>
{{msg}}
</div>
</template>
so how do i import mongodb to my vuejs 2 framework?
VueJS is frontend framework.
You definitely should not try to deal with DB directly from Vue.
You should have backend made with any language/framework you want: NodeJS(if you want to stick with JS), ASP.NET(C#), Spring(Java) etc. and your backend should deal with DB and you should only make AJAX requests to your backend and send/get back JSONs and deal with JSONs on frontend with Vue.
Related
I have learnt Nuxt JS and Spring MVC. I want to know, how to make a single page web application integrating or configuring Spring MVC and Nuxt JS. I didn't find any well documented material over internet. Basically, I want to handle all CRUD operations asynchronously. Database is MySQL. If possible, can someone help me how to do this? Thank you in advance!
I hope this will answer you, if I understand your question correctly.
Assuming, you have written the data access operations using Spring, Nuxt Js runs on port 3000, Tomcat on port 8080.
Let's say this is our RestController which fetches users data from database (using repository, service layer). Note the use of CrossOrigin - enabling cross origin request for restful web service which includes headers for Cross-Origin Resource Sharing (CORS) in the response. Here, we only allow localhost:3000 to send cross-origin requests. You can also go for Global CORS configuration.
#RestController
#RequestMapping("api")
#CrossOrigin(origins = "http://localhost:3000")
public class MainRestController {
private final IRestService restService;
#Autowired
public MainRestController(IRestService restService) {
this.restService = restService;
}
#GetMapping(value = "users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<String>> getUsers() {
try {
return new ResponseEntity<>(restService.getAllUsers(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
As you are using Nuxt js, this is our vue component which tries to access our REST end point which we created above. We are using axios to get our response here.
<template>
<div class="container">
<ul>
<li v-for="user of users">
{{user}}
</li>
</ul>
</div>
</template>
<script>
export default {
async asyncData({ $axios }) {
const users = await $axios.$get('http://localhost:8080/api/users');
return { users }
}
}
</script>
Your nuxt.config.js should contain this: the axios and proxy module should be installed.
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true,
},
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
},
proxy: {
'/api/': {
target: 'http://localhost:8080/',
pathRewrite: { "^/api": "" },
changeOrigin: true,
}
},
The axios settings for baseURL and browserBaseURL in nuxt.config.js are not being used by axios and the requests are going to localhost instead.
Here's an extract of nuxt.config.js:
modules: [
'#nuxtjs/axios'
],
axios: {
baseURL: 'http://192.168.8.137:8081',
browserBaseURL: 'http://192.168.8.137:8081'
},
And here's the code in the vue file:
<template>
<v-treeview
v-model="tree"
:open="open"
:items="items"
activatable
item-key="id"
:load-children="listDir"
:active.sync="active"
return-object
>
....
</template>
<script>
import axios from 'axios'
export default {
....
methods: {
async listDir(item) {
// let url = 'http://192.168.8.137:8081/filemanager/ls' // Works fine if hardcoded here
let url = '/filemanager/ls'
await axios.get(url)
.then(....
I think the problem is that I'm using axios.get(url) and not $this.axios.get(url), however my method is being called from a vuetify treeview component and $this is not available.
How do I get hold of $this.axios?
The code works fine if I hardcode the URL into the axios call.
using
import axios from 'axios'
you are importing "clean" axios module.
You need to use axios instance created by nuxt itself.
In component (or in Vue actions) use just (without importing axios)
this.$axios.get(...)
or (convenient $get method returns response data instead response object)
this.$axios.$get(...)
I am trying to generate a static website using nuxt with Json server Fake api server. I am just trying to pre-poplulate the static site with data from the json server using npm run generate. Thanks for all help!
<script>
import axios from 'axios'
export default {
async asyncData() {
const { data } = await axios.get('http://localhost:4000/gallery')
return { gallery: data }
}
}
</script>
<template>
<section class="gallery-grid">
<nuxt-link
v-for="i in gallery"
:key="i.id"
:to="'/'+i.id">
<img
:src="['gallery/'] + i.src + ['.jpg']"
:alt="i.title">
</nuxt-link>
</section>
</template>
Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.
There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using #types) to no avail.
Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.
The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts
import { Component, OnInit } from "#angular/core";
import { StitchClientFactory } from "mongodb-stitch";
let appId = 'authapp-****';
#Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})
export class MongoAuthComponent implements OnInit {
mClient;
ngOnInit() {
this.mClient = StitchClientFactory.create(appId);
}
And you can then use this for whatever purpose you want, such as for implementing sign-in with Google
gLogin(){
this.mClient.then(stitchClient => {
stitchClient.authenticate("google");
})
not sure whether the question is still relevant considering it was asked two months ago but anyway...
As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any
For example:
declare var stitch: any;
export class MyService implements OnInit {
db;
client;
ngOnInit() {
this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
this.client.login();
}
save() {
this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
}
}
the previous answers are functional, but i wanna share a example using a service injectable.
service.ts
import { Injectable } from '#angular/core';
import { Jsonp, URLSearchParams } from '#angular/http';
import { StitchClientFactory } from "mongodb-stitch";
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private jsonp: Jsonp) { }
client;
connect(){
this.client = new StitchClientFactory.create("App ID"); // Slitch apps > Clients > App ID
this.client.then(stitchClient => stitchClient.login())
.then((stitchClient) => console.log('logged in as: ' + stitchClient))
.catch(e => console.log('error: ', e));
}
all() {
this.connect();
return this.client.then(stitchClient => {
let db = stitchClient.service('mongodb', 'mongodb-atlas').db("database Name"); // Slitch apps > mongodb-atlas > Name database.Collection
let itemsCollection = db.collection('name collection'); // Slitch apps > mongodb-atlas > Name database.Collection
console.log(itemsCollection.find().execute());
return itemsCollection.find().execute();
})
.then(result => {return result})
.catch(e => console.log('error: ', e));
}
}
after make the previous file, you must create a module to receive the data, so:
module.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { StitchClientFactory } from "mongodb-stitch";
import { Service } from 'service'; // previous code
declare var stitch: any;
#Component({
template: '
<ul class="demo-list-icon mdl-list">
<li class="mdl-list__item" *ngFor="let item of data | async">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-icon">{{propiedad.nombre}}</i>
</span>
</li>
</ul>
'
})
export class MainComponent implements OnInit {
data: Observable<[]>;
constructor(private Service: service) {
}
ngOnInit() {
this.propiedades = this.Service.all();
}
}
important, you don´t must forget to add service on module.ts intitial declarations.
mongodb Atlas
mongodb-stitch vía NPM
Documentation mongoDB Stitch.
Sure!
Many tutorials and documentations later, I still cannot display data from Mongo in the Meteor client.
import { Mongo } from 'meteor/mongo';
export const Skills = new Mongo.Collection('skills')
Template.Skills.helpers({
skills: function() {
return Skills.find();
}
});
skills.html
<template name="Skills">
<h2>My Skills</h2><ul>
{{#each skills}}
{{> SkillItem}}
{{/each}}
</ul>
</template>
entering Skills.find(); in the developer console does not really do anything except give me the following error.
Exception in template helper: ReferenceError: Skills is not defined