ReactJS: JSON file is fetched from localhost instead of project directory - json

I have following directory structure of my project.
I have following code in my index.js file for loading website.json file.
index.js
componentDidMount() {
$.ajax({
url: "../website.json",
type: "GET",
dataType: 'json',
ContentType: 'application/json',
success: function(data) {
this.setState({data: data});
console.log(data);
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
}
The problem is that I am using npm start command to server my react app from local directory of my application. This serves my app at http://localhost:3000/ . Now the problem is that the application tries to load the website.json file from http://localhost:3000/website.json which gives a 404 not found error.
So, my question is how my website.json file can be loaded from my project directory instead of localhost.
Note: my project folder is not at localhost but at virtual host.
Update: I am specifically asking why the ajax call is unable to load data from my project folder (I am using relative addressing) and instead including path from localhost. I want to load data using ajax call is it possible or not.

Your webserver (I would guess Express) will be serving files from the 'public' folder.
For security reasons, web servers do not allow access to files outside of the directory root (/public in your case), so you will not be able to get the file by ajax (or from the browser).
If you really want to, you could either:
Copy/Move the file into the public folder
Create a symlink to the file in the public folder

You may include it inside source as
var website = require('../website.json');
So it will be embedded during compile time.
Another way to do it - move website.json to public folder, than you may access it as ajax('/website.json'...

I assume you are using ES6/ES2015 since you are using react. So instead of doing it in componentDidMount you can just add this at the top:
import websiteData from '../website.json';
And then you can just use websiteData as a variable in your component.

Related

Storyshots doesn't work on local storybook-static folder

Problem Summary
Storybook snapshot test on static storybook returning blank screenshots even though they look fine on localhost:8080 when I ran npx http-server storybook-static
Tech stack and relevant code
Vue 3
Vite
Storybook
Jest
Storyshots
Puppeteer
I have components and their respective stories. npm run storybook works perfectly fine. My storybook.spec.js is as follows:
import { imageSnapshot } from "#storybook/addon-storyshots-puppeteer"
import initStoryshots from "#storybook/addon-storyshots"
initStoryshots({
suite: "Image storyshots",
test: imageSnapshot(
storybookUrl: 'file://absolute/path/to/my/storybook-static'
)
})
I ran the following. fyi, I did not modify any file in storybook-static after running npm run build-storybook.
npm run build-storybook
npm run test
npm run test constitutes jest --config=jest.config.js test
Problem
Unfortunately, the screenshots I get are all blank and fail the snapshot test.
I suspect it might be due to a CORS error just like other Storybook users when they click <project-root>/storybook-static/index.html after running npm run build-storybook, to which I want to ask for a solution as well, because I wanna run test remotely on a headless server.
Note
I used absolute path because relative path caused a resource not found error during the testing process.
The problem is that you're running the tests from file:// instead of http://. So the URI is file:// and the img url ends up like this after applying some url logic: path.resolve(window.location, '/your-image.png') file:///your-image.png.
If this is the case you could change to http://. You can start a express server and serve the storybook-static folder from setupGlobal and then shut it down in teardownGlobal. Then you will need to change your storybookUrl to http://localhost:<some-port>.
None of the images were loading within my pipeline but worked fine locally, ended up being because the components were fetching images using a relative path <img src="/my-image" /> which apparently is not allowed using the file protocol.
I ended up doing 2 things:
Updating the static dirs directory to use the root by updating the main.js file in storybook
module.exports = {
staticDirs: [{ from: '../static', to: '/' }],
}
Added a script to remove the leading slash of images in the preview-head.html file from storybook
<script>
document.addEventListener('DOMContentLoaded', () => {
Array.from(document.querySelectorAll('img')).forEach((img) => {
const original = img.getAttribute('src');
img.setAttribute('src', original.replace('/', ''));
});
});
</script>
Another (arguably better) approach would be to run the tests through a server where you can access the images

How can i remove port from url to make source for images from xampp database to work properly?

I'm new to angular and i have a problem with angular and xampp. I'm trying to load images from mySQL database where i stored their destination. Problem is that angular tries to access that destination through this:
My HTML is:
But my url to that image is without port :4200
When i access localhost/bcPraca/php/upload/imageName then that image shows up so it works.
So how can i remove that port from Url. Or what can i do to make it work ?
Everything else is working properly except that source in the image.
You have to use a proxy in order to be able to communicate with your backend/
In order to use a proxy:
Create a proxy.conf.json in the root of your workspace (adapt the following to our needs):
{
"/api": {
"target": "http://localhost/api",
"secure": false,
"changeOrigin": true
"logLevel": "debug"
}
}
Start your app with the following command:
ng serve --proxy-config proxy.conf.json
You can read more about angular proxy here
You Can put prefix like http:// Before Your Image Source And It Will Work

PupeeteerSharp Does Not Work in ServiceFabric Stateless Service

I am developing web crawler which could render Javascript websites and so I decided to use PupeeteerSharp, a .NET port of popular Node.JS headless Chrome browser Pupeeteer API. I am running Service Fabric's local development cluster on Windows 10 development machine and have one stateless service in my solution.
I've created Data folder under Service project's PackageRoot folder and put .local-chromium folder contents there (contains chrome.exe executable) so it deploys as independent data package of service.
I've also placed this XML config line in ServiceManifest.xml file:
<DataPackage Name="Data" Version="1.0.0" />
So far it looks good and headless browser content is copied to SFCluster Data package directory properly.
Then in my Stateless Service code I try to call Pupeeteer chromium executable as follows:
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
ExecutablePath = _chromiumPath // #$"{context.CodePackageActivationContext.GetDataPackageObject("Data").Path}\.local-chromium\Win64-706915\chrome-win\chrome.exe"
});
using (var page = (await browser.NewPageAsync()))
{
Response renderResponse;
try
{
renderResponse = await page.GoToAsync(webPage.AbsoluteUri, timeout);
if (renderResponse.Status != System.Net.HttpStatusCode.OK)
{
return new RenderResult(RenderStatus.OtherFailure);
}
// other code
}
catch (TimeoutException)
{
return new RenderResult(RenderStatus.Timeouted);
}
In this line: using (var page = (await browser.NewPageAsync())) my code (Thread) simply hangs without returning, in Debug console I see many thread exits, but no exception occurs. I was previously getting System.IO.FileNotFoundException when I was fixing some other errors regarding appropriate copying of chromium folder contents, but now these errors are gone so it seems that code find .exe but somehow cannot start headless mode of PupeeterSharp.
Does that mean that I cannot simply run external .exe chromium binary with Service Fabric's Native Application Model? Should I use Docker and Linux containers instead?

The easiest routing in Fat-Free Framework (installed via Composer)

I want to configure the routes for my project via F3. First I installed him via Composer and then I used the instructions about routing engine from This and This.
Then in browser if I'm going to URL localhost/myproject/ it is working fine. But if I'm going to URL localhost/myproject/route1 it isn't working for me and gives 404 server status error. Why?
My code in "index.php":
require_once('vendor/autoload.php');
$f3 = \Base::instance();
$f3->route('GET /', function() {
echo '123';
});
$f3->route('GET /route1', function() {
echo '345';
});
$f3->run();
It is the easiest project without anything with only F3. Where I wrong?
make sure you got this .htaccess in your folder and in case that this does not help, comment in the RewriteBase / and adjust the path to match you sub-folder ("myproject").

Using Gulp+BrowserSync to automatically refresh web page and JSDoc Web page

I have my Gulp setup to automatically load/refresh my web page when application changes happen. However, I would also like to have it load my documentation page, and refresh that source each time as well.
I have it configured to be serving from two directories, but I do not know how to get it to load the second tab with the documentation directory.
[BS] Access URLs:
---------------------------------------
Local: http://localhost:3000
External: http://192.168.11.181:3000
---------------------------------------
UI: http://localhost:3001
UI External: http://192.168.11.181:3001
---------------------------------------
[BS] Serving files from: app/
[BS] Serving files from: docs/API.v1.1.0/
My gulpfile.js server section.
AppSync.init({
server: {
baseDir: [RootDir.home, RootDir.docs + DocumentationPath.javascript],
index: 'index.html',
directory: false, // Set to True for Browsing Files, not launching index
},
//open: false,
//reloadOnRestart: false
});
I have tried adding a second HelpSync using the BrowserSync.create() and set server variables, but this gives an error about re-using addresses, even when I specify a new port..
I am looking to have it start and load my App and API docs and keep refreshing both when I change any code. I can validate the application works, and that my API did document correctly.
I have been working with the BrowserSync and options, and found how to host two different paths, you simply use the Routes server option. This will keep two windows in sync as I wanted. The only issue is that I have to start the second window (for the API Documentation) by cloning the application window and changing the URL.
return AppSync.init({
server: {
baseDir: ['./'],
index: 'index.html',
directory: false, // Set to True for Browsing Files, not launching index
routes: {
'/API': 'APIV1.0.0/,
"/app": 'app/'
}
},
port: 3000,
startPath: '/app'
});
Adding the startPath will get the Application window loaded on a refresh, and start up. However, I do have to clone this window, and change the address to get the API documentation showing. Once this is done though, both windows will update on a file change. It would be nice to get both windows opened, but that is still outstanding.
Basically, I'm using the BrowserSync.reload() method within all the important tasks, e.g.
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gulp = require('gulp');
var sass = require('gulp-sass');
// Sass task, will run when any SCSS files change.
gulp.task('sass', function () {
return gulp.src('scss/styles.scss')
.pipe(sass({includePaths: ['scss']})) // compile sass
.pipe(gulp.dest('css')) // write to css dir
.pipe(filter('**/*.css')) // filter the stream to ensure only CSS files passed.
.pipe(**reload**({stream:true})); // inject into browsers
});
// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
As documented here