In a react native app, I am following the documentation of expo-file-system to upload an image from the gallery of my phone and send it to a node.js server that uses multer to process the file. Unfortunately, I am having the following error when I send the http request:
Possible Unhandled Promise Rejection (id: 1):
Error: Failed to connect to localhost/127.0.0.1:3000
I know that the server is working because I have tested it with the same client but using axios and fetch to send the request and it reached the server.
This is the code that I am using in the client side:
//.env
URL = 'http://localhost:3000/api/upload'
//uploadImage.js
import React, { useState } from "react";
import { View, Button, Image, StyleSheet } from "react-native";
import * as ImagePicker from 'expo-image-picker'
import * as FileSystem from 'expo-file-system';
import {URL} from "#env"
const ImageUpload = ()=>{
const [image, setImage] = useState('')
const [name, setName] = useState('')
const [type, setType] = useState('')
const openImageLibrary = async()=>{
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log('this is the result',result);
if (!result.canceled) {
const uri = result.assets[0].uri
const filename = uri.split('/').pop();
const match = /\.(\w+)$/.exec(filename);
const imageType = match ? `image/${match[1]}` : `image`;
setImage(uri);
setName(filename)
setType(imageType)
}
}
const sendPictureToServer = async()=>{
const response = await FileSystem.uploadAsync(URL ,image,{
fieldName: 'photo',
httpMethod: 'POST',
uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT,
})
}
return(
<View>
<Button title = 'select' onPress={openImageLibrary}/>
<Button title='send' onPress={sendPictureToServer}/>
</View>
)
}
This is the node.js server
//index.js
const Express = require('express')
const multer = require('multer')
const bodyParser = require('body-parser')
const app = Express()
app.use(bodyParser.json())
const upload = multer({ dest: 'uploads/' } )
app.get('/', (req, res) => {
res.status(200).send('You can post to /api/upload.')
})
app.post('/api/upload', upload.single('photo'), (req, res) => {
console.log('file', req.file)
console.log('body', req.body)
res.status(200).json({
message: 'success!',
})
})
app.listen(3000, () => {
console.log('App running on http://localhost:3000')
})
Related
It must show console log Big Number instead its showing error.
expected output
error occured
I am new to blockchain. I have connected the private key of hardhat with wallet but its showing Type Error. The expected output and the output which Ive got has attached along with this.
import React, { useState, useEffect } from "react";
import { ethers, BigNumber } from "ethers";
import Web3Modal from "web3modal";
//INTERNAL IMPORT
import {
checkIfWalletConnected,
connectWallet,
connectingWithBooToken,
connectingWithLIfeToken,
connectingWithSingleSwapToken,
connectingWithIWTHToken,
connectingWithDAIToken,
} from "../Utils/appFeatures";
import { IWETHABI } from "./constants";
// import ERC20 from "./ERC20.json";
export const SwapTokenContext = React.createContext();
export const SwapTokenContextProvider = ({ children }) => {
const swap = "Welcome to swap my token";
//USESTATE
const [account, setAccount] = useState("");
const [ether, setEther] = useState("");
const [networkConnect, setNetworkConnect] = useState("");
const [weth9, setWeth9] = useState("");
const [dai, setDai] = useState("");
const [tokenData, setTokenData] = useState([]);
const addToken = [
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"0x15Ff10fCc8A1a50bFbE07847A22664801eA79E0f",
"0xAe9Ed85dE2670e3112590a2BB17b7283ddF44d9c",
];
//FETCH DATA
const fetchingData = async () => {
try{
//GET USER ACCOUNT
const userAccount = await checkIfWalletConnected();
setAccount(userAccount);
//CREATE PROVIDER
const web3modal = new Web3Modal();
const connection = await web3modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
//CHECK Balance
const balance = await provider.getBalance(userAccount);
console.log(balance);
}catch(error){
console.log(error);
}
}
useEffect(()=>{
fetchingData();
},[]);
return (
<SwapTokenContext.Provider value={{swap}}>
{children}
</SwapTokenContext.Provider>
);
};
your imports are probably failed try to import like this instead :
const ethers = require("ethers");
const BigNumber = require("ethers");
I have built a simple koa framework application.After adding routes am trying to hit the /health GET route. It throws the below error:
TypeError: next is not a function
at cookieParser (c:\Userxxs\x\gimt\dp-my-app\node_modules\cookie-parser\index.js:46:14)
at dispatch (c:\Users\B748806a\gimt\dp-my-app\node_modules\koa-compose\index.js:42:32)
at bodyParser (c:\Users\B748806a\gimt\dp-my-app\node_modules\koa-bodyparser\index.js:95:11)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Below are the files and their order of execution:
server.js
const app = require("./app.js");
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port: ${PORT}`));
app.js
"use strict";
const koa = require('koa');
const koaRouter = require('koa-router');
const app = new koa();
const router = new koaRouter();
const middleware = require("./src/main/middlewares/middlewares");
const routes = require("./src/main/middlewares/route-path");
const init = async () => {
try {
/**
* Step 2: load endpoint routes for the application
*/
routes(router)
} catch (err) {
logger.error({
err
});
}
};
/**
* Step 1: load middleware setup - cors,helmet from KP Spring cloud service
*/
middleware(app);
init();
module.exports = app
middleware.js
const koa = require("koa");
const koaRouter = require('koa-router');
const router = new koaRouter();
const cors = require("koa-cors");
const compression = require("koa-compress");
const helmet = require("koa-helmet");
const cookieParser = require("cookie-parser");
const bodyParser = require('koa-bodyparser')
const ActuatorRouter = require('pm-js-actuator').koa //internal library
const ACTUATOR_OPTIONS = {
health: {
enabled: true
},
livenessprobe: {
enabled: true
},
env: {
enabled: false
},
info: {
enabled: true,
secure: false
}
}
function middleware(app) {
// Use the CORS for the time being.
app.use(cors())
// Let's don the security helmet
app.use(helmet())
app.use(helmet.frameguard())
app.use(helmet.ieNoOpen())
app.use(helmet.frameguard({
action: 'sameorigin'
}))
app.use(helmet.noSniff())
app.use(helmet.referrerPolicy({
policy: 'same-origin'
}))
app.use(helmet.xssFilter())
//app.disable('x-powered-by')
app.use(ActuatorRouter.getRouter(ACTUATOR_OPTIONS).routes())
app.use(bodyParser())
app.use(cookieParser());
// Set up compression
app.use(compression());
}
module.exports = middleware;
route-path.js
const RootHeathController = require("../controller/root-health-controller")
const routes = (router) => {
router.get("/health", RootHeathController.handler)
};
module.exports = routes
root-health-controller.js
const handler = async (ctx, next) => {
ctx.body="Hi";
}
module.exports = {
handler
};
The application is started successfully on port 3000. But when i hit, /health from postman, it throws the mentioned error. Any solution?
The problem here is, that cookie-parser seems to be an express - thing (see also repo url: https://github.com/expressjs/cookie-parser). So to test this I created a minimal version of your code:
const koa = require('koa');
const koaRouter = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cookieParser = require("cookie-parser");
const app = new koa();
app.use(bodyParser());
app.use(cookieParser()); // <-- comment this line
const router = new koaRouter();
router.get("/health", async (ctx, next) => {
ctx.body = 'hi';
});
app.use(router.routes());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port: ${PORT}`));
Calling the localist:3000/health endpoint throws the same error. But if you comment the app.use(cookie-parser()) line all works fine.
The question is, why you would need this library? You should be able to set and get cookies in koa with ctx.cookies.get and ctx.cookies.set
I am getting this error in my heroku logs.
Same Question
All the solutions provided here did not address the issue.
I tried the different variations of the get method:
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
What else could I try or am I missing from here?
App.js
const configuration = require('#feathersjs/configuration');
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const moment = require('moment');
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
const app = express(feathers());
app.feathers().configure(configuration());
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
// Parse JSON
app.use(express.json());
// Configure SocketIO realtime API
app.configure(socketio());
// Enable REST services
app.configure(express.rest());
// Register services
app.use('/ideas', new IdeaService());
// Connect new streams
app.on('connection', conn => app.channel('stream').join(conn));
// Publish events to stream
app.publish(data => app.channel('stream'));
const PORT = process.env.PORT || 3030;
app.listen(PORT).on('listening', () => console.log(`Server running on port ${PORT}`));
app.service('ideas').create({
text: 'Build a cool app',
tech: 'Node.js',
viewer: 'John Doe'
});
export default IdeaService;
package.json
This code, containing two effects, returns no data. However, when commenting out either one, data is returned normally.
When both effects are run, dev-tools network view shows vehicleList request headers 'Provisional' and vendorList with a status code of `500 Internal Server Error'.
Is it possible to request two effects in the same functional component? If yes, how?
PowMaintenance.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { PowForm } from './PowForm';
const server = `http://${process.env.REACT_APP_API_BACK_END_ADDRESS}:${
process.env.REACT_APP_API_BACK_END_PORT
}`;
const PowMaintenance = () => {
const [vehicleList, setVehicleList] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(`${server}/api/vehicle/VehicleList`);
setVehicleList(result.data);
};
fetchData();
}, []);
const [vendorList, setVendorList] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(`${server}/api/vendor/VendorList`);
setVendorList(result.data);
};
fetchData();
}, []);
console.log('vehicle', vehicleList);
console.log('vendor', vendorList);
return (
<div>
<PowForm vendorList={vendorList} onChange={onChange} />
</div>
);
};
export { PowMaintenance };
```
Yozi, thank you for your help. You were correct, it was in the API. I researched it only because of your insistence.
A programming error in TDS/MSSQL involving connections.
Need to handle Apollo graphql errors globally in client side and render custom ErrorHandler component on error . So I used Apollo's afterware and apollo-link-error
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error'
const httpLink = new HttpLink({ uri: '/graphql' });
const logoutLink = onError(({ networkError }) => {
if (networkError.statusCode === 401) {
//need to dispatch a redux action so that ErrorHandler component renders
}
})
const client = new ApolloClient({
link: logoutLink.concat(httpLink),
});
My solution for this (which I guess, is not the correct approach)
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { render } from 'react-dom';
import ErrorHandler from '../utils/ErrorHandler';
const httpLink = new HttpLink({ uri: '/graphql' });
const logoutLink = onError(({ networkError }) => {
if (networkError.statusCode === 401) {
const targetDiv = document.getElementById('serviceErrorHandler');
render(
<ErrorHandler message={networkError.message}/>,
targetDiv
);
}
})
const client = new ApolloClient({
link: logoutLink.concat(httpLink),
});
Please suggest an approach for my scenario. Thanks in advance
Had this same problem, one solution we went with was making a function that returns onError and take a parameter (the store):
const errorHandler = store => onError((errors) => {
if (errors.networkError) {
store.dispatch(createApolloErrorAction({
message: GENERIC_ERROR_FETCHING_STRING,
}));
}
});
And use it in a wrapper functions to pass in the store:
let apolloClient = null;
export const createApolloClient = (reduxStore) => {
const cache = new InMemoryCache();
const link = errorHandler(reduxStore).concat(otherLink);
apolloClient = new ApolloClient({ link });
return apolloClient;
};
export const getApolloClient = () => apolloClient;