I'm new to node js and vue development and I want to create a process where I can create and upload a JSON file to my server when the user saves data in a form. This process should be done in the background. Later I want to read and update that file from the server when the user changed something.
So my first idea was to use fs.writeFile() this doesn't work very well and I think this only works for local stuff is that correct?
var fs = require('fs')
export default {
methods:{
send(){
fs.writeFile("/test.json","Hello World!",function(err){
if(err){
throw err;
}
});
}
}
}
Furthermore it looks like fs.writeFile doens't work with vue because it throws this error:
TypeError: fs.writeFile is not a function at VueComponent
So my second idea was to use express js with the app.post('/api/apps',...) and app.get() method. Here I have no idea how to implement that into the vue framework because I have to call the api like mydomain.com/api/apps but this doesn't work too.
So what is the best way to create, read, upload, delte files into a specific folder on my server? And how it works with vue? I tend to express js.
I'm using vue cli :)
Thanks in advance :)
EDIT
Now what I do is:
I created a new folder in my vue project root and named it "backend". In this folder I created a file named index.js and put this code
app.post('/appjson',(req,res) => {
fs.writeFile("/appjson/myJson.json",req.body,function(err){
//handle error
});
});
on the client side I put this code
axios.post('myDomain.com/appjson', {
JSONdata: myJSONdata,
})
My project looks like:
So when I build I get the dist folder and this I can upload on my server and it works fine. But I can't do the call to my backend? Whats wrong do I call the wrong link? Or how can I access my backend? Is the project struture correct or do I need to add the backend to a specific folder?
Vue is client side, your code is trying to write something to the filesystem of the user thats using your website. what you want to do is send this data to your NodeJS server, this requires using a package like Axios to send data to and from the server without refreshing the page. Axios is pretty straight forward to use, what you need will look similar to the function below.
saveJSON (myJSONData) {
const url = myNodeJSURL/savescene
return axios.post(url, {
JSONdata: myJSONdata,
})
Read some tutorials on ExpressJS, It's a pretty painless framework to use. You'll get the data stored in the body of the HTTP request and then you can use fs.writeFile to save data to the local filesystem of your server. Let me know if you need more help.
EDIT:
Your front end needs to be access a domain or IP address associated with your back end in order to communicate with it. Add the snippet below to your ExpressJS application and then when you run the server any requests to localhost:3000 will be handled by your app. You'll also have to update the URL in your Axios call.
app.listen(3000, function () {
console.log('my server is listening on port 3000!')
})
this setup only works for testing purposes because client and server will have to be on the same machine for localhost to mean the same to both. If you want this project to be public then you need to get your own domain for your site and host the ExpressJS application through there. Google compute makes this pretty easy to do, I'd look into that if I were you.
Related
I am currently working on a Sessions Server for a company project.
My problem is, I cant find any help to accomplish, that I can do javascript HTTP calls from a javascript server running with http.createServer() and server.listen(8080, ...) to my Angular Server, which is hosted with ng serve running on localhost:4200.
What I want, respectively need,is something like mentioned below in pseudocode:
In my Angular TypeScript file I need something like:
private listdata = new Array<string>();
ngOnInit(){}
constructor(private http: HttpClient){
this.http.listen(method: "POST", address: "http://localhost:4200/data", callback: => (data){
this.listdata = data;}
)
}
So that my Angular Application (Server) can receive REST calls from another Server.
In my JavaScript file I want to do smth. like:
http.post("localhost:4200/data", data, httpOptions);
So in the end, my javascript server running on localhost:8080 sends data to my angular server running on localhost:4200.
I tried to read me through several sources, containing HttpInterceptors etc. but couldnt find a simple solution for Noobs like me.
Is there an easy way, so that my automatically builded and hosted Angular Server can define routes it listens to and process the data directly for frontend use?
Thanks in advance :)
I think you have to read documentation again
In my opinion or am using like that when calling rest.
2.1 Rest function have to write in httpService.service.ts
2.2 Rest I used to HttpInterceptor to login OAUTH it will check auth guards,
then token expired you check easy way.
3. last question: You asking like roles something, you want to show components different users? yes you can manage routing,
https://www.thirdrocktechkno.com/blog/how-to-integrate-interceptor-in-angular-9/
I can't for the life of me figure this out, it seems like it should be straight forward but it's just not clicking.
I have an ES6 app that I created using create-react-app. I've got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app - like a botched MVC where React handles the views and I run the models and controllers in PHP.
So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn't yet compatible with a number of browsers but that's a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function...
let test = fetch('../models/overall-stats.php').then(function(response) {
console.log(response);
return response;
});
...the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I'm requesting.
If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn't be using fetch what's a better approach to this problem I'm having?
When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.
Any help would be greatly appreciated.
I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.
Why don't you just use something like ${baseUrl}/models/... ?
Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!
Maybe you can try to use ajax to get or post the data from server, just like this:
$.ajax({
url: '../models/overall-stats.php',
data: {
},
type: 'GET',
dataType : 'json',
success : function(res){
let obj = parseJSON(res)
}
})
or add this on top in your php file because the CORS :
header('Access-Control-Allow-Origin: *');
I've set up a meteor app using iron-router and I want the app to listen to a webhook from another service (basically I'm building an API for other services to use)
So for example, when an external website calls myapp.meteor.com/webhook I want to catch that specific link and parameters and do stuff with the data.
Update: Thanks to a comment I found this: https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#server-routing
Router.route('/webhooks', { where: 'server' })
.post(function () {
console.log(this);
this.response.end('Caught you\n');
//this.response.status(200).json({text:"Todo added"});
});
I added the above in the /server folder as there is no need to for the front-end server to worry about this like mentioned in the comment. But when I load this using postman POST request, it just returns my HTML for not found. Any ideas?
Thanks in advance for your help.
UPDATE
I tried what #David said and still I get the template loaded and nothing in the console. Any idea what I'm doing wrong?
Your server route will only run if no client routes also match. I suspect you have a catch-all route which is executing on the client and preventing the server route from running. One solution is to define all of the routes in a common folder like /lib so that you can properly order them. Your routes file could look something like:
client route 1
client route 2
server route 1
server route 2
catch-all (not found) route
When you have a RESTful server which only responds with JSON by fetching some information from the database, and then you have a client-side application, such as Backbone, Ember or Angular, from which side do you test an application?
Do I need two tests - one set for back-end testing and another set for front-end testing?
The reason I ask is testing REST API by itself is kind of difficult. Consider this code example (using Mocha, Supertest, Express):
var request = require('supertest');
var should = require('chai').should();
var app = require('../app');
describe('GET /api/v1/people/:id', function() {
it('should respond with a single person instance', function(done) {
request(app)
.get('/api/v1/people/:id')
.expect(200)
.end(function(err, res) {
var json = res.body;
json.should.have.property('name');
done();
});
});
});
Notice that :id in the url? That's an ObjectId of a specific person. How do I know what to pass there? I haven't even looked into the database at this point. Does that I mean I need to import Person model, connect to database and do queries from within the tests? Maybe I should just move my entire app.js into tests? (sarcasm :P). That's a lot of coupling. Dependency on mongoose alone means I need to have MongoDB running locally in order to run this test. I looked into sinon.js, but I am not sure if it's applicable here. There weren't many examples on how to stub mongoose.
I am just curious how do people test these kinds of applications?
Have you tried using mongoose-model-stub in your server-side test? It will free you from having to remember or hardcode database info for your tests.
As for testing the client side, your "webapp" is basically two apps: a server API and a client-side frontend. You want tests for both ideally. You already know how to test your server. On the client you would test your methods using stubbed out "responses" (basically fake json strings that look like what your web service spits out) from your API. These don't have to be live urls; rather it's probably best if they're just static files that you can edit as needed.
I would use nock..https://github.com/pgte/nock
What you want to test is the code you have written for your route.
So what you do is, create a response that will be sent when the end point is hit.
Basically its a fake server..
Something like this..
Your actual method..
request({
method: "GET",
url: "http://sampleserver.com/account"
}, function(err, res, data){
if (err) {
done(err);
} else {
return done(null,data);
}
});
Then..
var nockObj = nock("http://sampleserver.com")
.get("/account")
.reply(200,mockData.arrayOfObjects);
//your assertions here..
This way you don't alter the functionality of your code.. Its like saying.. instead of hitting the live server..hit this fake server and get mock data. All you have to do is make sure your mock data is in sync with the expected data..
This question should be simple to answer for anyone with Node experience -- unfortunately I am an extreme novice.
I am writing a web application for a board game that will use a server-client architecture to show real-time changes made to the board to all clients. The application uses Raphael to display the graphics.
I have created a server that successfully sends the HTML file to respond to any request, but the board does not display -- only the raw HTML without any Javascript comes up. I think it is because I have programmed the server to always respond with the HTML file, and I can't figure out how to send the Javascript files (client.js, raphael.js) to the client so that the page can load properly.
The relevant code is below. For now, I'm just trying to get the browser to draw one Raphael element so I can see that the client is properly getting the Javascript files it needs to load the page.
On the server side:
var fs = require('fs');
var server = require('http').createServer(function(req, response){
fs.readFile('index.html', function(err, data) {
response.writeHead(200, {'Content-Type':'text/html'});
response.write(data);
response.end();
});
});
On the client side:
$(document).ready(function(){
var R = Raphael("container", 1000, 700);
this.R.path("M0,0l1000,700").attr({"stroke-width": "5"});
});
You can assume that the HTML file is formatted correctly and includes references to all the JS files -- I've had the application working great without the server-client architecture for a while now. Also, I am using NowJS, so any solution that incorporates that framework would be welcome as well.
Thanks for any help!
on your server side you are always returning index.html
check out how the createServer method is used in this gist: https://gist.github.com/1245922
it evaluates the extension to return a proper mime-type and then calls the stream file function to return the requested url/file from the fs.
if you're going to use this with nowjs then you'll want to also use along the lines of:
var everyone = nowjs.initialize(server);
Use the static middleware
http://senchalabs.github.com/connect/middleware-static.html