How can I import an image from the express server to the client (in React) - node.js

I'm trying to show an image in react, which is neither a local image (in the client) nor an external image from the web but an image that is in the node.js express server (and I don't want to call it as if it was an external image, because the domain could change and it just doesn't seem right).
I know I can't just import it like I do with a local image in the client because we're speaking about different localhosts. I did try this:
loadImage = async (imageUrl) => {
const response = await fetch(`/api/images/${imageUrl}`);
const data = await response.json();
this.setState({ image: data });
}
componentDidMount() {
const { imageUrl } = this.props;
try {
this.loadImage(imageUrl);
} catch(error) {
console.log("Hay un error: " + error);
}
}
render() {
const { image } = this.state;
return(
<div>
<div>
<img alt="dontknowyet" className="blog-list-image" src={image} // and so on...
{image} does receive the correct path, but the image won't load and the console throws this error:
Not allowed to load local resource: file:///C:/Users/Dafna/Desktop/adrian/proyectos/esteticand/img/t4.jpg
So how can I make it work? and in case that I need to import the image file instead of just the link, how can I do that? (I can't update the state with an image...)

In order to access the path of the image it has to be done through the express server.
For example, if the (backend) server is running on port 4500 and the image is in a folder called images, and the express variable is called app, in the server file you have to use:
app.use(express.static('images'));
and then the image can be accessed in http://localhost:4500/nameoftheimage.jpg.

Do you have the api running on the same port as the React app?
You usually would make them run on different ports. Maybe it's got something to do with it.

Related

Query parameters not received from deep linking - react native(expo) and node js

I am using openAuthSessionAsync to do a call to my backend and sending the url for deep linking
I am redirected back successfully to my app but i don't get query parameters that i send from backend with deep link
My react native app side:
const experiment = async()=>{
try{
let result = await WebBrowser.openAuthSessionAsync(`http://myaddress :3901/api/testig?linkingUri=${Linking.createURL(
"/?",
)}`,);
console.log(result)
}catch(errr){
console.log(errr)
}
}
My node js side:
router.get("/testig",(req,res)=>{
url = req.query.linkingUri
**//url is exp://myaddress:19000/--/?**
res.redirect(url+"?authToken=abc123")
})
I have also tried hard coding the url in backend but it only opens app back but with no parameters
And in my react native side in console i get this:
Object:{
"type":"dismiss",
}
UPDATE: Solved it by setting up eventListener for LINKING as follows
const handleDeepLink = (event)=>{
let data = Linking.parse(event.url)
setdata(data)
if(JSON.parse(data.queryParams.isSuccessful) == true)
{
props.navigation.navigate("thankyou")
}
}
React.useEffect(()=>{
Linking.addEventListener("url",handleDeepLink)
return(()=>{
Linking.removeEventListener("url")
})
},[])
use trycarch in the block to see errors and use var url
code lookslike
router.get("/testig",(req,res)=>{
try {
var url = req.query.linkingUri
return res.redirect(url+"?authToken=abc123")
} catch (e) {
console.log(e)
}
})

Dynamic file names in react native require()

We're working on an app that will allow users to store templates with images on them, and pull those templates up later. This is for an AR environment using Viro on React Native.
We're trying to dynamically load an image into the component, and receiving errors when we require the filepath, which has been set to a variable:
const exampleUri = '/some/uri'
render() {
return(
<Viro3DObject
source={require(exampleUri)}
/>)
}
The URI for the source prop has to be dynamic, as the URIs are pulled from a Database.
We've tried storing the entire request in the database (in models/element.js):
const Sequelize = require('sequelize');
const db = require('../db');
const Element = db.define('element', {
sourceViro3DObject: {
type: Sequelize.STRING
}
});
sourceViro3DObject: `require('../../assets/emoji_heart/emoji_heart.vrx')`
When we called it in the React Native class component:
getObjectData = async () => {
try {
const {data} = await axios.get(`/api/elements/${this.props.elementId}`)
this.setState({sourceViro3DObject: data.sourceViro3DObject})
} catch (err) {
console.log(err)
}
}
async componentDidMount() {
await this.getObjectData()
}
But this simply sets state.sourceViro3DObject to a string:
'require('../../assets/emoji_heart/emoji_heart.vrx')'
We've tried setting the filepath directly to state as a string:
state.sourceViro3DObject = '../../assets/emoji_heart/emoji_heart.vrx'
and then call require on it:
require(this.state.sourceViro3DObject)
and received the following error:
Invalid prop `source` supplied to `Viro3DObject`
We've seen recommendations of storing the URIs in an object, but that can't work for us as we don't know what image is going to be used until it's pulled from the database. We can't hard-code them anywhere.
We'd appreciate any help with this!

Use server to download image and serve to frontend

I'm running into a CORS issue trying to pull images from S3 (Converting Image URL to base64 - CORS issue).
I'm just using the images for a few seconds while I am generating a PDF file. Is there a way that I can have Meteor download the image and serve for just a few seconds so that I can get around the CORS problem?
I can't have Meteor just serve the images all the time since there are a ton of them and they change for the different reports.
I ended up getting around the CORS issue by doing this:
import { request } from "meteor/froatsnook:request";
Meteor.methods({
convertImage: function(imageUrl) {
try {
var result = request.getSync(imageUrl, {encoding: null});
return 'data:image/png;base64,' + new Buffer(result.body).toString('base64');
} catch(e) {
throw new Meteor.Error("cant-download", "Error: Can't download image.");
}
}
});

Using react-hot-loader 3 with own server

I was able to set up react-hot-loader to work properly bundling my client js and pushing changes to browser and applying there (except [react-router] You cannot change <Router routes>; it will be ignored warning).
I'm using my own server with koa, koa-webpack-dev-middleware and koa-webpack-hot-middleware, that processes webpack and hot. It also handles server rendering of my app with this code
export default function *renderReact() {
const history = createMemoryHistory();
const store = makeStore(history);
const [redirectLocation, renderProps] = yield match.bind(null, { routes, location: this.url, history });
if (redirectLocation) {
return this.redirect(redirectLocation.pathname + redirectLocation.search)
}
if (renderProps == null) {
return this.throw(404, 'Not found')
}
const rootElement = (
<Provider store={store} key="provider">
<RouterContext {...renderProps} />
</Provider>
);
this.body = renderApp({
html: yield store.renderToString(ReactDOMServer, rootElement),
state: JSON.stringify(store.getState())
});
}
The problem is with my server side code: hot works only for client code and updates changes on the fly, but my server code does not get updated on changes as scripts a loaded on server start and on page reload i get not updated rendered page from server and then it updates with new client code.
and react warning Warning: React attempted to reuse markup in a container but the checksum was invalid...
The question is: how to handle code changes related to server rendering part on server not restarting the app as it breaks hot loading?

Get source url for image stored in Bluemix Object Storage container using Node.js app

I have an Object Storage instance on Bluemix where I am storing images in the container. I need a source url for the images stored there so that I can use that image. To do this, I'm thinking of creating a Node.js app so that I will write a post call where I'll pass image name present in Object Storage as request, so that it will give me the image url as response.
Is this possible or not? If possible, can anyone suggest whether there are any npm modules which do this functionality? If not, are there any other suggestions to get the url of image?
Any help is appreciated..Thanks!
start the server by command node app.js also u need package pkgcloud to perform this operation. You can get the object storage credentials simply by creating a key on IBM console inside Storage module.
inside app.js insert a new route for download
var objectStorageHandler = require("./lib/objectStorageHandler.js");
app.get('/download', function(req, res) {
(new objectStorageHandler()).download('YourContainerName', 'imagenamewithextension',function(download){
console.log(res);
download.pipe(res);
});
});
Inside Lib folder create a module with name objectStorageHandler.js
Inside objectStorageHandler.js write code
var pkgcloud = require('pkgcloud');
var objectStorageHandler = function(){
}
objectStorageHandler.prototype.download = function(container, file,callback)
{
var config = {
provider: 'openstack',
useServiceCatalog: true,
useInternal: false,
keystoneAuthVersion: 'v3',
authUrl: 'https://identity.open.softlayer.com',
tenantId: 'YOURPROJECTID', //projectId from credentials
domainId: 'YOURDOMAINID',
username: 'YOURUSRNAME',
password: 'YOURPASSWORD',
region: 'dallas' //dallas or london region
};
var client = pkgcloud.storage.createClient(config);
client.auth(function (error) {
if(error) {
console.error("Authorization error for storage client (pkgcloud): ", error);
}
else {
var request = client.download({
container: container,
remote: file
});
callback(request);
}
});
}
module.exports = objectStorageHandler;
after server started lets assume at port 3000 simply call localhost:3000/download that will download the image, we can also pass image name in parameters to download images dynamically.

Resources