Cypress cy.request returns 404 - http-status-code-404

I am using Cypress with react and node express server. I am trying to build a test that starts by calling cy.request with post method in order to initialize the state of the app for this particular test, but the response is always 404 as the following
Error:
CypressError: cy.request() failed on:
mysite.net
The response we received from your web server was:
404: Not Found
This was considered a failure because the status code was not '2xx' or '3xx'.
If you do not want status codes to cause failures pass the option: 'failOnStatusCode: false'
The request does work in prod/dev (status 200) but in cypress it always returns 404 as mentioned. I also checked the data structure of the request and it seems ok.
I am using the same route for all, the only difference is the method I use:
dev/prod: standard fetch API call seats under an apiHandler function.
Cypress: cy.request() method
My code:
cy.request({
method: 'POST',
url: `auth/login/example-url`,
failOnStatusCode: false,
form: true,
body: {
arrival: '2021-12-01T17:23',
departure: '2021-12-01T15:23',
destination: 'New York',
origin: 'Washington DC',
},
})
Thanks ahead for your help:)

when Browser: send request header and response status code OK
Using cy.visit(): response status code Not Found
So the problem is the Request Headers, you better check it, and set Headers in cy.visit() to look like Browser Headers. you'll receive the status code OK.

Related

CORS error with react native app run with expo web [duplicate]

I created an API endpoint using Google Cloud Functions and am trying to call it from a JS fetch function.
I am running into errors that I am pretty sure are related to either CORS or the output format, but I'm not really sure what is going on. A few other SO questions are similar, and helped me realize I needed to remove the mode: "no-cors". Most mention enabling CORS on the BE, so I added response.headers.set('Access-Control-Allow-Origin', '*') - which I learned of in this article - to ensure CORS would be enabled... But I still get the "Failed to fetch" error.
The Full Errors (reproducible in the live demo linked below) are:
Uncaught Error: Cannot add node 1 because a node with that id is
already in the Store. (This one is probably unrelated?)
Access to fetch at
'https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5'
from origin 'https://o2gxx.csb.app' has been blocked by CORS policy:
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response.
GET
https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5 net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
See Code Snippets below, please note where I used <---- *** Message *** to denote parts of the code that have recently changed, giving me one of those two errors.
Front End Code:
function getCSC() {
let lat = 37.75;
let lng = -122.5;
fetch(
`https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=${lat}&lon=${lng}`,
{
method: "GET",
// mode: "no-cors", <---- **Uncommenting this predictably gets rid of CORS error but returns a Opaque object which seems to have no data**
headers: {
// Accept: "application/json", <---- **Originally BE returned stringified json. Not sure if I should be returning it as something else or if this is still needed**
Origin: "https://lget3.csb.app",
"Access-Control-Allow-Origin": "*"
}
}
)
.then(response => {
console.log(response);
console.log(response.json());
});
}
Back End Code:
import json
import math
import os
import flask
def nearest_csc(request):
"""
args: request object w/ args for lat/lon
returns: String, either with json representation of nearest site information or an error message
"""
lat = request.args.get('lat', type = float)
lon = request.args.get('lon', type = float)
# Get list of all csc site locations
with open(file_path, 'r') as f:
data = json.load(f)
nearby_csc = []
# Removed from snippet for clarity:
# populate nearby_csc (list) with sites (dictionaries) as elems
# Determine which site is the closest, assigned to var 'closest_site'
# Grab site url and return site data if within 100 km
if dist_km < 100:
closest_site['dist_km'] = dist_km
// return json.dumps(closest_site) <--- **Original return statement. Added 4 lines below in an attempt to get CORS set up, but did not seem to work**
response = flask.jsonify(closest_site)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
return response
return "No sites found within 100 km"
Fuller context for code snippets above:
Here is a Code Sandbox Demo of the above.
Here is the full BE code on GitHub, minus the most recent attempt at adding CORS.
The API endpoint.
I'm also wondering if it's possible that CodeSandbox does CORS in a weird way, but have had the same issue running it on localhost:3000, and of course in prod would have this on my own personal domain.
The Error would appear to be CORS-related ( 'https://o2gxx.csb.app' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.) but I thought adding response.headers.set('Access-Control-Allow-Origin', '*') would solve that. Do I need to change something else on the BE? On the FE?
TLDR;
I am getting the Errors "Failed to fetch" and "field access-control-allow-origin is not allowed by Access-Control-Allow-Headers" even after attempts to enable CORS on backend and add headers to FE. See the links above for live demo of code.
Drop the part of your frontend code that adds a Access-Control-Allow-Origin header.
Never add Access-Control-Allow-Origin as a request header in your frontend code.
The only effect that’ll ever have is a negative one: it’ll cause browsers to do CORS preflight OPTIONS requests even in cases when the actual (GET, POST, etc.) request from your frontend code would otherwise not trigger a preflight. And then the preflight will fail with this message:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
…that is, it’ll fail with that unless the server the request is being made to has been configured to send an Access-Control-Allow-Headers: Access-Control-Allow-Origin response header.
But you never want Access-Control-Allow-Origin in the Access-Control-Allow-Headers response-header value. If that ends up making things work, you’re actually just fixing the wrong problem. Because the real fix is: never set Access-Control-Allow-Origin as a request header.
Intuitively, it may seem logical to look at it as “I’ve set Access-Control-Allow-Origin both in the request and in the response, so that should be better than just having it in the response” — but it’s actually worse than only setting it in the response (for the reasons described above).
So the bottom line: Access-Control-Allow-Origin is solely a response header, not a request header. You only ever want to set it in server-side response code, not frontend JavaScript code.
The code in the question was also trying to add an Origin header. You also never want to try to set that header in your frontend JavaScript code.
Unlike the case with the Access-Control-Allow-Origin header, Origin is actually a request header — but it’s a special header that’s controlled completely by browsers, and browsers won’t ever allow your frontend JavaScript code to set it. So don’t ever try to.

Axios XMLHttpRequest - Network error on body exceeding a certain size

I'm trying to POST a file as a base64 string to my API from a react app using axios. Whenever the file seems to exceed a certain (small ~150ko) size, the request is not sent and axios/xhr throws a Network error:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Any ideas?
It seems that basic POST requests using axios are capped in there file size. Using multipart form data for those uploads (populating a form with my file) seems to solve the pb
Source
But ultimately we moved to uploading directly to our AWS/S3 using a signed uri provided by our backend.
The problem is your type: of your file might not be valid one as per the MIME type. please check in your console
There might also be the problem of repeating the baseURL which means NETWORK_ERROR 404 NOT FOUND like of.. so please see the example below
let formData = new FormData();
formData.append("files", {
uri: payload.uri,
name: payload.name,
type: `payload.type?payload.type:image/${fileExt}` //this should be a valid Mime type
});
axios.post(`v2/upload_comment_file`, formData, {
headers: {
...(await HeaderData()),
"Content-Type": "multipart/form-data",
},
});
find mime type might get lil tricky for some image and doc picker lib like expo-doc-picker in ver 35.. please try react-native-mime-types https://www.npmjs.com/package/react-native-mime-types which helped me out and can help you too

Angular $http.post returns 404 error

I am using angular JS to send some data to Payment Gateway.
Syntax for curl to send data as per documentation is:
curl https://www.mybank.co.uk/3dsecure
-H "Content-type: application/x-www-form-urlencoded"
-X POST
-d 'TermUrl=https://www.yourmerchantsite.co.uk/3DSecureConfirmation&PaReq=value-of-oneTime3DsToken&MD=merchantdatavalue'
However when I am doing it in Angular :
$http({
method: 'POST',
url: 'url',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html'
},
data: $.param({TermUrl: obj.TermUrl ,Pareq: obj.Pareq }),
})
I am getting error
Possibly unhandled rejection: {"data":"<html><head><title>400 Bad
Request</title></head><body><h1>Bad Request</h1></body>
</html>","status":400,"config":
{"method":"POST","transformRequest":[null],"transformResponse":
[null],"jsonpCallbackParam":"callback","url":"payement gatway
url","headers":{"Content-Type":"application/x-www-form-urlencoded",
"Accept":"text/html,application/xhtml+xml"},"data":"TermUrl=url&Pare
q=value"},"statusText":"Bad Request","xhrStatus":"complete"}
Kindly suggest how to proceed with this one ?
First of all, you are experiencing a 400 Bad Request (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) and not a 404 Not Found.
It usually means that you are not sending the right data to the server and the API is expecting some specific parameters (from the body usually).
Check the API, look at every parameter required from it - their types and how they should be sent (body param? query string? etc...).
You can use your browser network tab or tools like Postman to see what you are actually sending to the server and if it matches what the server is expecting you to send.
Check out 3D Secure's API reference, you should get back a detailed error code beside the http status code:
https://developer.paysafe.com/en/3d-secure/api/#/introduction/error-summary/common-errors
It should be easily debuggable.

Can't get any response back while calling service through frisbyJS

The code I am using is:
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....')
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();
The error I get while running it from CLI using
jasmine-node EndpointTest_spec.js
The error I get is:
Error: Expected 500 to equal 200
Error: Header 'content-type' not present in HTTP response
So do I need to first load my website and call services through my application and then run frisby ?
But then it defeats the purpose of just making a quick check for all the endpoints used in application without running it.
You are calling request with https:// which may be secure server so use
{ strictSSL: false} in your get method .get('https://services.....',{ strictSSL: false}). It will solve your problem.
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....',{ strictSSL: false})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

Resources