React ES6 App - Local API calls - javascript

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: *');

Related

Is there any way to save a full XHR payload in a cypress run?

We have our cypress suite working fine locally in every machine, environment, location.
We've configured it to work with a Bitbucket pipeline but there is a specific step that consistently fails because of the API call it makes. This API call is made to an external service and we are adding params in the payload that are dynamically built with the request.
Our suspicion is that there are some of these params that are not built correctly when running it from the pipeline (may be related to location, agent, etc) because we are getting "Unauthorized".
So the issue is that we don't have any way to debug this API call from the pipeline and it is the only place where it fails.
So, do you have any suggestions on how to save the XHR Payload in a step in Cypress?
Store it in a mocha report.
Send it via email.
Maybe add it to a log.
Save it as an artifact.
I'm sorry I'm just clueless how to approach this as I'm not an expert in neither cypress nor bitbucket pipelines.
More specifically, I need to debug this call:
As I understand, your external API call URL is known, right? If so, I would suggest for debugging purpose to route this call, then display it out in the cypress running logs, so you will be able to compare the request payloads:
cy.route({ method: 'POST', url: `/ps/users`}).as('routedRequest');
...
cy.get('#routedRequest').then((xhr) => {
cy.log(JSON.stringify(xhr.request))
});

How to REST call Angular TypeScript Server with JavaScript

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/

Upload JSON File to my server with vue and node js

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.

AngularJS: Retrieving Videogular templates stored in $templateCache results 404 Error

I currently develop an AngularJS 1.5.9 Single Page Application on my localhost with NodeJS running backend, where I use
Videogular framework. http://www.videogular.com/
Everything is fine except inserting videogular object on my page. I strictly follow the given example: http://www.videogular.com/examples/simplest-videogular-player/
<videogular vg-theme="controller.config.theme.url">
<vg-media vg-src="controller.config.sources"
vg-tracks="controller.config.tracks"
vg-native-controls="true">
</vg-media>
</videogular>
But it results in AngularJS error:
(sessionId in the request is the auth token not linked to current problem)
I have found the following in videogular.js :
$templateCache.put("vg-templates/vg-media-video", "<video></video>");
$templateCache.put("vg-templates/vg-media-audio", "<audio></audio>");
I have tried to store files locally, and the error disappeared
Actually there are a lot of plugins for Videogular and they all are using $templateCache to store some files in the cache, so it would be very confusing to manually store them locally in my app folder.
How can such files be stored in the cache using $templateCache so they can be extracted properly?
I apreciate your help.
UPDATE
I have tried insert $templateCache.get to directive, where the part is loading with error 404, and it works. But still doesn't work as it supposed to be.
It seems like there is an issue with sessionId that you pass in URL parametrs, do you actually need it?
I guess your interceptor or whatever auth managing module is wrong configured, so you don't check request target URL and id parameters are going to be added for local calls as well as for backend calls.

Making an AJAX request with jQuery from PhoneGap app to Node JS server

I've been looking around on the internet to see a real example of a jQuery AJAX request to a Node JS server, but can't find it.
So normally a jQuery AJAX request to a PHP server looks like this:
$("button").click(function() {
$.ajax({url: "http://www.example.org/myphpfile.php", success: function(result) {
console.log(result);
}});
});
But how does this JS code look when a request must be made to a Node JS server? I've not seen any example that has a URL to a .js file on the server, but we do include a URL to a PHP file when a request is made to a PHP server.
So in short, what does a jQuery AJAX request to a Node JS server look like? Or are there any additional libraries or frameworks needed to achieve this?
NodeJS dosent work like that.
You set up and start the server on a port let say http://localhost:3000 and you send all request to it.
You can use a web application framework like Express to define routes more like .htaccess in php does. You setup functions on those routes.
So a typical call to a NodeJS looks like
http://localhost:3000/route1
route1 isn't a file its a route configured by a web application framework like Express to perform a task (or function) when the route is reached
So jQuery has nothing to do with it. You can still use it has it was just let url point to the route defined by Express
$("button").click(function() {
$.ajax({url: "http://www.example.org/getWhatever", success: function(result) {
console.log(result);
}});
});
This tutorial will help https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters
This Book is great www.packtpub.com/web-development/mean-web-development

Categories