Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing request token for request, while uploading image file getting error. #29021

Closed
sahilpandya opened this issue Jun 1, 2020 · 79 comments
Closed
Labels
🌐Networking Related to a networking API. Platform: Android Android applications. Platform: iOS iOS applications. Resolution: Locked This issue was locked by the bot.

Comments

@sahilpandya
Copy link

sahilpandya commented Jun 1, 2020

Missing request token for request, while uploading image file getting error.

Description

While image is uploading to server, sometime its throwing error Missing request token.

React Native version: v0.61.5

Run react-native info in your terminal and copy the results here.

System:
OS: macOS Mojave 10.14.6
CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Memory: 147.43 MB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 10.16.3 - ~/.nvm/versions/node/v10.16.3/bin/node
Yarn: 1.21.1 - /usr/local/bin/yarn
npm: 6.9.0 - ~/.nvm/versions/node/v10.16.3/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 13.0, DriverKit 19.0, macOS 10.15, tvOS 13.0, watchOS 6.0
IDEs:
Xcode: 11.0/11A420a - /usr/bin/xcodebuild
npmPackages:
react: 16.12.0 => 16.12.0
react-native: 0.61.5 => 0.61.5
npmGlobalPackages:
react-native-cli: 2.0.1

Steps To Reproduce

Provide a detailed list of steps that reproduce the issue.

  1. Add an image from camera and add an image from library.
  2. then upload images to server.

Expected Results

Images should be uploaded successfully.

Snack, code example, screenshot, or link to a repository:

IMG_613148776FD6-1

@khuyendev
Copy link

same issue here

@MaxEgg
Copy link

MaxEgg commented Jun 13, 2020

Having this issue constantly in version: 0.63.0-rc.0. Can not upload a file. Tried using the fetch api and Axios. Both throw this error when adding formData with image data to the request. Adding formData with a string value still works as expected.

@linoleum00
Copy link

I'm using RN 0.62.2, and I'm having this issue. I'm using rxjs/ajax to upload to a multipart POST API and it crashes!

@sahilpandya
Copy link
Author

sahilpandya commented Jun 29, 2020

I got one work around, adding setTimeout for each request, So now am able to upload 90% times. But it is still not 100% workaround.

here is a sample code:
return new Promise(function(resolve, reject) { setTimeout(() => { return request.put(file, options) .then(response => { // success resolve() }) .catch((err) => { reject(err); }); }, 1500); }) .catch(error => { // error })

@linoleum00
Copy link

I also read this same workaround, and as you said it is not a 100% solution, sometimes it still crashes

@HugoGresse
Copy link

HugoGresse commented Jul 9, 2020

I've updated the app to RN 0.63 and reproduce this 100% o the time, either on emulator or iPhone...
To be more clear, the image doesn't even go out of the device, using Charles proxy doesn't show any network usage upon upload.

@wezzy
Copy link

wezzy commented Jul 9, 2020

Same here, after the upgrade if I make a request using fetch("SOME LOCAL PATH") I get the error. It's woking correctly with the older version

@kelset
Copy link
Contributor

kelset commented Jul 10, 2020

Since this seems to be surfacing more with the new 0.63, can someone who is facing this issue please post a full repro? Meaning, a sample react-native init'd project with the minimal code to reproduce the issue posted above.

@v-anton
Copy link

v-anton commented Jul 13, 2020

100% reproducible on 0.63 (iOS).

@dharminderraja
Copy link

same here i am using react-native-aws3 to upload the image and it always have this error.
this error start happening when i updated the rn to 0.63 was working fine in previous version of rn.

@struct78
Copy link

struct78 commented Jul 13, 2020

Have tested this using fetch to read an image with the file protocol and get the same error. Replacing the file:/// URL with a https:// URL works fine.

I don't have time to put it in an easily reproducible demo unfortunately.

https://github.com/trueme-app/trueme-react-native/blob/develop/src/services/s3.ts#L36

Having dug a bit deeper (and not fully understanding how RN workers under the hood, so I apologise in advance if I'm wrong!), I wonder if this commit is the culprit? 058eeb4 @p-sun

@leops
Copy link

leops commented Jul 13, 2020

I stumbled upon this problem too, quickly looking at it it seems to me the origin for the problem is this function:

- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
{
__block RCTImageLoaderCancellationBlock requestToken;
requestToken = [self loadImageWithURLRequest:request callback:^(NSError *error, UIImage *image) {
if (error) {
[delegate URLRequest:requestToken didCompleteWithError:error];
return;
}
NSString *mimeType = nil;
NSData *imageData = nil;
if (RCTImageHasAlpha(image.CGImage)) {
mimeType = @"image/png";
imageData = UIImagePNGRepresentation(image);
} else {
mimeType = @"image/jpeg";
imageData = UIImageJPEGRepresentation(image, 1.0);
}
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:mimeType
expectedContentLength:imageData.length
textEncodingName:nil];
[delegate URLRequest:requestToken didReceiveResponse:response];
[delegate URLRequest:requestToken didReceiveData:imageData];
[delegate URLRequest:requestToken didCompleteWithError:nil];
}];
return requestToken;
}

When loading a file from the local filesystem loadImageWithURLRequest can (and does) load the file synchronously, and calls the callback block immediately. Since the function hasn't returned yet requestToken is not initialized, hence the "Missing request token" error

@v-anton
Copy link

v-anton commented Jul 13, 2020

I stumbled upon this problem too, quickly looking at it it seems to me the origin for the problem is this function:

- (id)sendRequest:(NSURLRequest *)request withDelegate:(id<RCTURLRequestDelegate>)delegate
{
__block RCTImageLoaderCancellationBlock requestToken;
requestToken = [self loadImageWithURLRequest:request callback:^(NSError *error, UIImage *image) {
if (error) {
[delegate URLRequest:requestToken didCompleteWithError:error];
return;
}
NSString *mimeType = nil;
NSData *imageData = nil;
if (RCTImageHasAlpha(image.CGImage)) {
mimeType = @"image/png";
imageData = UIImagePNGRepresentation(image);
} else {
mimeType = @"image/jpeg";
imageData = UIImageJPEGRepresentation(image, 1.0);
}
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:mimeType
expectedContentLength:imageData.length
textEncodingName:nil];
[delegate URLRequest:requestToken didReceiveResponse:response];
[delegate URLRequest:requestToken didReceiveData:imageData];
[delegate URLRequest:requestToken didCompleteWithError:nil];
}];
return requestToken;
}

When loading a file from the local filesystem loadImageWithURLRequest can (and does) load the file synchronously, and calls the callback block immediately. Since the function hasn't returned yet requestToken is not initialized, hence the "Missing request token" error

Hey @leops
Please let me know if you need any help. Looking forward to a solution, but can't manage it due to another work tasks :(

@stonecoder19
Copy link

Having the same issue

@kelset kelset added the Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. label Jul 15, 2020
@github-actions
Copy link

⚠️ Missing Reproducible Example
ℹ️ It looks like your issue is missing a reproducible example. Please provide a Snack or a repository that demonstrates the issue you are reporting in a minimal, complete, and reproducible manner.

@struct78
Copy link

Here is a minimal repo that demonstrates this error. Choose a file from the camera roll and then try to retrieve that using fetch.

https://github.com/struct78/react-native-0.63.1-missing-request-token

@uusa35

This comment has been minimized.

@imoby

This comment has been minimized.

@uusa35
Copy link

uusa35 commented Jul 21, 2020

fixed the error

before i was fetching image.path and it was working just fine.

now u have to pass the sourceURL as the following

Screen Shot 2020-07-21 at 8 12 17 AM

@imoby
Copy link

imoby commented Jul 21, 2020

@uusa35 can you provide a code sample? I was pulling the uri too and it was still failing for me

@dorthwein
Copy link

Originally our fetch body was being set to { uri: photoUri, name: fileName, type: "image/png" }. In v0.63 this stopped working.

Using @uusa35 method and restructuring the body to ["image", { uri: photoUri, name: fileName, type: "image/png" }] the fetch goes through, but does not actually upload the file. S3's url returns an empty image file.

So it seems that the body needs to be an array(?) instead of a simply hash to go through? @uusa35 can you please elaborate on your fetch request and possibly include an example?

@ejung-park
Copy link

ejung-park commented Sep 2, 2020

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

@GreatAuk
Copy link

GreatAuk commented Sep 2, 2020

0.63.2 still exist

@tamhv
Copy link

tamhv commented Sep 3, 2020

I am using 0.63.2 and the problem still present. I use apollo-upload-client to upload files.
Please advise.

Update: temporarily solved by adding =^{} after the request token.

@kockok could you please explain more on your solution, i'm using ReactNativeFile with apollo-upload-client to upload file

@edritech93
Copy link

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

still issue

@abemusic
Copy link

abemusic commented Sep 4, 2020

@FabrizioCaldarelli -- I also didn't want to patch, so thank you for the rn-fetch-blob suggestion. Works great!

@kockok
Copy link

kockok commented Sep 4, 2020

I am using 0.63.2 and the problem still present. I use apollo-upload-client to upload files.
Please advise.
Update: temporarily solved by adding =^{} after the request token.

@kockok could you please explain more on your solution, i'm using ReactNativeFile with apollo-upload-client to upload file

Edit this file: react-native/Libraries/Image/RCTImageLoader.mm to __block RCTImageLoaderCancellationBlock requestToken = ^{};

@ASakkeer
Copy link

ASakkeer commented Sep 4, 2020

I am using 0.63.2 and the problem still present. I use apollo-upload-client to upload files.
Please advise.

Update: temporarily solved by adding =^{} after the request token.

I have tried " __block RCTImageLoaderCancellationBlock requestToken = ^{};" on "node_modules/react-native/Libraries/Image/RCTImageLoader.mm" this file. Then I deleted my App on IOS and again I run the application using "yarn ios". But, still having the issue. Did I missed something? @kockok @tamhv @akkravikumar

@PetrVasilev
Copy link

I have the same issue. When it will be fixed?

@VonJie
Copy link

VonJie commented Sep 5, 2020

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });
IOS : photo.uri.replace("file://", "/private")

still issue

thanks, it works for me.

@AbhijithMohan007
Copy link

@VonJie Thanks man

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

this is work for me too..

@devkrkanhaiya
Copy link

devkrkanhaiya commented Sep 18, 2020

in
node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm file

Replace Below

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }

return nil;
}

With

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    __block auto cancelled = std::make_shared<std::atomic>(false);
    RCTExecuteOnMainQueue(^{
    if (cancelled->load()) {
    return;
    }

    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }
    });

    return ^{
    cancelled->store(true);
    };
    }

This..

Like and Love , if it work 👍

@eco-line
Copy link

This got fixed in v0.63.3

@cherucole
Copy link

This got fixed in v0.63.3

I upgraded RN to this version and never saw the issue again

@safaiyeh
Copy link
Contributor

safaiyeh commented Oct 9, 2020

Thanks everyone for your patiences. Glad the fix is in, closing

@safaiyeh safaiyeh closed this as completed Oct 9, 2020
@thaiphamvan
Copy link

dataForm.append('file', { uri: Platform.OS=='ios'?photo.uri.replace("file://", "/private"):photo.uri, name: 'photo.jpg', type: 'image/jpg' });

IOS : photo.uri.replace("file://", "/private")

thanks , It works for me.

@Balasnest
Copy link

getting this npm error after change package json from 0.63.2 to 0.63.3.

npm ERR! code EINTEGRITY
npm ERR! Verification failed while extracting jsc-android@241213.1.0:
npm ERR! Verification failed while extracting jsc-android@241213.1.0:
npm ERR! sha512-AH8NYyMNLNhcUEF97QbMxPNLNW+oiSBlvm1rsMNzgJ1d5TQzdh/AOJGsxeeESp3m9YIWGLCgUvGTVoVLs0p68A== integrity checksum failed when using sha512: wanted sha512-AH8NYyMNLNhcUEF97QbMxPNLNW+oiSBlvm1rsMNzgJ1d5TQzdh/AOJGsxeeESp3m9YIWGLCgUvGTVoVLs0p68A== but got sha512-ptI+efRlVdodigsznoyx5zuvQcHCk3NgWkC8GR/qr2pRl87wCpMDqzDs/zvKfm3zkBALvOaF2E/gD5DePG4G4Q==. (4273248 bytes)

Any idea?

@Leehee1on
Copy link

node_modules/react-native/Network/NetworkTesk.mm

Line 102 ~ 107

if (requestToken == nil) {
if (RCT_DEBUG) {
// RCTLogError(@"Missing request token for request: %@", _request); // change
}
valid = YES; // change NO -> YES
}

My solution is RN < 63.2

@GuilhermeTrivilin
Copy link

Error fixed when updating React Native to version 0.63.3

@tbsphpdev
Copy link

tbsphpdev commented Jan 12, 2021

This working for me
data.append('image',
{
uri: Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', '/private'),
name: 'image.jpg',
type: 'image/jpg',
});

@MahmudHasanMenon
Copy link

I also faced same issue. But I manually updated the RCTNetworkTask.mm file. I know it is not correct method but at least I can upload the image now until React-Native developer share their fix to us.

node_modules/react-native/Libraries/Network/RCTNetworkTask.mm

- (BOOL)validateRequestToken:(id)requestToken
{
  BOOL valid = YES;
  if (_requestToken == nil) {
    if (requestToken == nil) {
      if (RCT_DEBUG) {
//        RCTLogError(@"Missing request token for request: %@", _request);
      }
      valid = YES;
    }
    _requestToken = requestToken;
  } else if (![requestToken isEqual:_requestToken]) {
    if (RCT_DEBUG) {
      RCTLogError(@"Unrecognized request token: %@ expected: %@", requestToken, _requestToken);
    }
    valid = NO;
  }

  if (!valid) {
    _status = RCTNetworkTaskFinished;
    if (_completionBlock) {
      RCTURLRequestCompletionBlock completionBlock = _completionBlock;
      [self dispatchCallback:^{
        completionBlock(self->_response, nil, RCTErrorWithMessage(@"Invalid request token."));
      }];
    }
    [self invalidate];
  }

  return valid;
}

thank you very much. It is working

@michaelVictoriaDev
Copy link

still get error in 0.63.4

@victorglomer
Copy link

victorglomer commented Mar 27, 2021

In my case, thats what worked

    const data = new FormData();
    data.append("avatar", {
      type: "image/jpeg",
      name: `${user.id}.jpg`,
      uri:
        Platform.OS == "ios"
          ? response.uri?.replace("file://", "/")
          : response.uri,
    });

@rdewolff
Copy link

In my case, thats what worked

    const data = new FormData();
    data.append("avatar", {
      type: "image/jpeg",
      name: `${user.id}.jpg`,
      uri:
        Platform.OS == "ios"
          ? response.uri?.replace("file://", "/")
          : response.uri,
    });

This worked for me too! Thanks for sharing.

@facebook facebook locked as resolved and limited conversation to collaborators Oct 9, 2021
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Oct 9, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
🌐Networking Related to a networking API. Platform: Android Android applications. Platform: iOS iOS applications. Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests