I use react-native-image-picker to upload image to a server. I use the following code:
sendPhoto = async () =>{
const fileToUpload = {
type:'image/jpg',
uri: 'file://'+this.state.photo.path,
name:'uploadimage.jpg'
}
console.log(fileToUpload);
let data = new FormData();
data.append('file_attachment', { type:'image/jpg', uri: this.state.photo.path, name:'uploadimage.jpg'})
fetch (settings.ajaxurl+'sickFishUpload',{
method: 'POST',
body: data,
headers: {
'Content-Type': 'multipart/form-data; ',
},
})
.then( (response) => response.json())
.then((res) => {
console.log(res);
//console.log(res);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
})
}
Unfortunatelly It cannot communicate with the server. I got this message: There has been a problem with your fetch operation: TypeError: Network request failed.
If I erase this json from the data:
{ type:'image/jpg', uri: this.state.photo.path, name:'uploadimage.jpg'}
it can communicate with the server.
I set the AndroidManifest.xml with
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and the application tag with
android:requestLegacyExternalStorage="true"
I'm totally stucked. Do you have any idea what is wrong? Of course I 've found this question in a previous post, but It is more than a years old and my solution is worked with the previous version of react-native. So I don't know how to upgrade my code...
Every suggestion is very welcome.
thx
Adam
Related
I am trying to resolve this 401 issue for some time. After logging in and obtaining the token I am setting it as a header, but keep getting 401 exception on first load of the page. The error goes away after refresh. It seems that the token is not written to store or localStorage the first time around. Here's my code for login (I set the token to state.token in the mutation):
retrieveToken(context, credentials) {
return new Promise((resolve, reject) => {
axios.post('api/login', {
email: credentials.email,
password: credentials.password,
})
.then(response => {
const token = response.data.access_token
localStorage.setItem('access_token', token)
context.commit('RETRIEVE_TOKEN', token)
resolve(response)
console.log(response.data)
})
.catch(error => {
console.log(error)
reject(error)
})
})
},
And that's how I set it to header (setting it from localStorage doesn't solve the issue):
const authorizedApiClient = axios.create({
baseURL: process.env.VUE_APP_PRODUCTION_URL,
headers: {
Accept: 'application/json',
'Authorization': `Bearer ${store.getters.token}`
}
})
This behavior baffles me. Is there any theory or suggestions on how to debug?
I guess when the axios client is created the token is not yet retrieved from api. Try setting the header before each request using an interceptor:
const authorizedApiClient = axios.create({
baseURL: process.env.VUE_APP_PRODUCTION_URL,
headers: {
Accept: 'application/json'
}
})
authorizedApiClient.interceptors.request.use((config) => {
if (store.getters.token){ // or get it from localStorage
config.headers["Authorization"] = "Bearer " + store.getters.token
}
return config
})
I have the following nodejs code per this and this:
const WebSocket = require('ws');
const ws = new WebSocket('wss://ws.tradier.com/v1/markets/events');
request({
method: 'post',
url: 'https://api.tradier.com/v1/markets/events/session',
form: {
},
headers: {
'Authorization': 'Bearer MY_API_KEY_NOT_SHOWN',
'Accept': 'application/json'
}
}, (error, response, body) => {
console.log(response.statusCode);
console.log(body);
let data = JSON.parse(body)
let sessionId = data.stream.sessionid
streamPrice(sessionId)
});
function streamPrice(sessionId){
console.log(sessionId)
ws.on('open', function open() {
console.log('Connected, sending subscription commands...');
ws.send(`{"symbols": ["TSLA"], "sessionid": "${sessionId}", "linebreak": true}`);
});
ws.on('message', function incoming(data) {
console.log(data);
});
ws.on('error', function error(data) {
console.log(data);
});
}
I get a 200 OK back from the API request to create the web sockets session, and I have a valid session ID:
200
{"stream":{"url":"https:\/\/stream.tradier.com\/v1\/markets\/events","sessionid":"6ba4158d-8ff8-46c3-b005-***********"}}
6ba4158d-8ff8-46c3-b005-***********
However, the ws.on() events never fire. I am not getting any errors. The session does close after a period of time, presumably due to inactivity. But it's not inactivity on my code's part...
Is there something wrong in my code / something I'm missing to make this work?
I was able to identify the issue myself. The problem is I was opening the websocket too early.
I moved the following line inside of streamingPrice scope instead of the global scope to resolve.
const ws = new WebSocket('wss://ws.tradier.com/v1/markets/events');
After trying to use the app on an android device and simulator, the result is the same, I'm getting a 401 (unauthenticated). The problem seems to be weird, as the homescreen does fetch the objects properly, but on another view, same thing, 401 (only on android).
The axios call I'm doing is the following:
async getSubject(){
const token = await AsyncStorage.getItem('access');
const access = 'Bearer ' + token;
axios.get(`http://example.com/api/auth/subject/${this.props.navigation.getParam('id')}`, {
headers: {
'Authorization': access,
}
})
.then(res => {
this.setState({ subject: res.data.subject })
this.setState({ loading: false });
this.setState({ refreshing: false })
})
}
My backend is laravel, I'm using passport. But still, not sure why it only works fine on iOS and not in android.
Why is this happening?
I am using Nativescript 5 and Angulat 4, and I am trying to download an image using a get request using #angular/http
getImageFile(path){
let headers = new Headers();
headers.set("Content-Type", "image/jpeg");
return this.http.get((encodeURI(this.serverUrl + path)),{method: RequestMethod.Get,
responseType: ResponseContentType.Blob, headers: headers })
.map(res => res);
}
But it returns
Error: Response type of 'blob' not supported.
So I remove responseType: ResponseContentType.Blob and it works.
But when trying to get the information
this.myGetService.getImageFile('api/imagen/')
.subscribe(
response =>{
try{
var blob = new Blob([response.blob()], {type: 'image/jpeg'});
}catch(err){
console.log("Super Error !!!!", err);
}
}, (error) => {
console.log("Error Request: " + error);
});
Now it throws an exception.
Super Error !!!! ReferenceError: Can't find variable: Blob
It's an open feature request to support Blob format with the HttpClient in {N} Angular.
A workaround could be using the getFile method on the default Http module.
I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.