I'm running JavaScript tests using Karma but it fails to make http requests.
build.gradle.kts
js(IR) {
useCommonJs()
browser {
testTask {
useKarma {
useChromeHeadless()
}
}
}
binaries.executable()
}
I'm using Ktor Client to fetch the url content
val text = HttpClient(Js).get("https://www.google.com/") {
header("Content-Type", "text/html; charset=utf-8")
header("Accept", "*/*")
}.body<String>()
And this is the error:
> Task :jsTestClasses
> Task :compileTestDevelopmentExecutableKotlinJs
> Task :jsTestTestDevelopmentExecutableCompileSync
> Task :jsBrowserTest
myTest before fetch
TRACE: Adding Accept-Charset=UTF-8 to https://www.google.com/TRACE: Processing exception Error_0: Fail to fetch for request https://www.google.com/Error_0: Fail to fetch
at http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52793:26
Caused by: TypeError: Failed to fetch
at commonFetch (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52730:13)
at $executeCOROUTINE$16.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52105:29)
at JsClientEngine.execute_95skru_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:52224:16)
at HttpClientEngine$executeWithinCallContext$slambda.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46100:44)
at HttpClientEngine$executeWithinCallContext$slambda.invoke_1yhb3o_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46082:16)
at l (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:46133:16)
at _no_name_provided__qut3iv_6.doResume_5yljmg_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31198:43)
at CoroutineImpl.resumeWith_7onugl_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31062:33)
at CoroutineImpl.resumeWith_s3a3yh_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:31108:17)
at DispatchedTask.run_mw4iiu_k$ (http://localhost:9876/absolute/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_293805/commons.js?58a2b80ce49dc5767b060dfe37192606438b082a:41652:24)
Trying to make the same request using window.fetch:
val response = window.fetch(url).await()
println("response: ${response.body}")
This fails with:
> Task :jsTestTestDevelopmentExecutableCompileSync
> Task :jsBrowserTest
getFileText before fetch
TypeError: Failed to fetch
TypeError: Failed to fetch
at 2.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3883)
at <global>.httpGet(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3765)
at 1.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3845)
at HtmlResourceLoader.getFileText_6u54xq(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3920)
at slambda.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:992)
at slambda.invoke_pbb09x(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:978)
at slambda.$block(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:1023)
at slambda.doResume_5yljmg(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3792)
at slambda.invoke_d6gbsu(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3778)
at <global>.l(/var/folders/cb/nd4gn6pn79zg52rz_l5bl1bdjfnmjy/T/_karma_webpack_124481/commons.js:3825)
I had to enable cors in Express server.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
https://expressjs.com/en/resources/middleware/cors.html
Related
I have a Svelte application and I am trying to render data from the API but I keep on getting 3 error messages.
The code works properly on node but not on Svelte.
Below is the Svelte code:
<script lang="ts">
import { onMount } from "svelte";
let word = [];
onMount(async () => {
const response = await fetch(
"https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5",
{
method: "GET",
headers: {
"X-RapidAPI-Key": "KEY",
"X-RapidAPI-Host": "random-words5.p.rapidapi.com",
},
}
);
word = await response.json();
console.log(word);
});
</script>
<p>{word}</p>
And below are the error messages:
ross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:5173’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS request did not succeed). Status code: (null).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
How do I get my code to render out the data from the API in Svelte?
The CORS issue occurs when you try to fetch a resource from a local environment, this is the case when you run your app in dev mode.
I use the CORS Unblock extension to fix the issue, give it a try.
I have a Localhoset and want to get the data from this local host in Flutter and show it with clicking on the button.
the get request successfully finishes but the nstead of printing the result i recieve the following error!
> Running with unsound null safety
For more information see https://dart.dev/null-safety/unsound-null-safety
Debug service listening on ws://127.0.0.1:59432/vuDMHfesIRs=/ws
DioError [DioErrorType.response]: XMLHttpRequest error.
dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 909:28 get current
packages/dio/src/dio_mixin.dart 819:20 assureDioError
packages/dio/src/dio_mixin.dart 678:13 _dispatchRequest
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 60:31 <fn>
dart-sdk/lib/async/zone.dart 1618:54 runBinary
dart-sdk/lib/async/future_impl.dart 169:20 handleError
dart-sdk/lib/async/future_impl.dart 719:46 handleError
dart-sdk/lib/async/future_impl.dart 740:13 _propagateToListeners
dart-sdk/lib/async/future_impl.dart 550:5 [_completeError]
dart-sdk/lib/async/future_impl.dart 606:7 callback
dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 <fn>
I test the same code and the same Process with anothe api it was working!
what could it be?
here is the get method:
Dio dio = new Dio();
void getCountries() async{
try {
var response = await dio.get('http://b21dfa1ea157.ngrok.io/gettest'
);
dio.options.headers['content-Type'] = 'text/plain; charset=UTF-8';
dio.options.headers['Access-Control-Allow-Origin'] = '*';
dio.options.headers['Access-Control-Allow-Methods'] = 'GET , POST';
print(response.data);
} catch (e) {
print(e);
}
}
and also through clicking the Button it calls the method:
RaisedButton(onPressed: getMethod)
Could anybody help me?
This seems to be a CORS (cross-origin resource sharing) issue. Common workarounds made here for development builds is by disabling security using --disable-web-security argument when the app is run.
For production builds, you need to enable the CORS request on your server-side to fix this. Depending on your setup, you won't be needing to make changes on the client app.
I am new to flutter development. I am trying hard to make the https calls work. Whenever I call a https url, it throws the below error:
SocketException: Failed host lookup: 'someserver.com' (OS Error: nodename nor servname provided, or not known, errno = 8)
Below is the code I am using,
final ioc = new HttpClient();
ioc.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
final http = new IOClient(ioc);
return http
.post(url, body: body, headers: headers, encoding: encoding)
.then((response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while posting data");
}
return _decoder.convert(res);
});
I have checked below few links and many more and tried all of them but nothing seems to work.
How to solve SocketException: Failed host lookup: 'www.xyz.com' (OS Error: No address associated with hostname, errno = 7)
https://github.com/flutter/flutter/issues/27883
Also please note that I am able to access the server from the browser. Same server is being access from iOS app as well(built using XCode). From iOS I am able to access the server.
Kindly help!!!
The http package provides the simplest way to fetch data from the internet.
To install the http package, add it to the dependencies section of the pubspec.yaml file. You can find the latest version of the http package to here
dependencies:
http: <latest_version>
Import the http package.
import 'package:http/http.dart' as http;
Additionally, in your AndroidManifest.xml file, add the Internet permission.
<uses-permission android:name="android.permission.INTERNET" />
Then like the below function, you will be able to get/fetch/post HTTP call
Future<http.Response> getchData() {
return http.get('https://jsonplaceholder.typicode.com/albums/1');
}
For Advanced HTTP call and management you can use Dio plugin
When I connect to Socket.io on the server I get a 400 error, but I don't see any errors connecting to localhost. (same code and connecting via socket.io-objc)
I'm using Azure to host the node.js project.
(I also have websockets on in the azure config if that makes a difference)
ERROR: handshake failed ... The request timed out.
onError() Error Domain=SocketIOError Code=-6 "The operation couldn’t be completed.
(SocketIOError error -6.)" UserInfo=0x1874cc00 {NSUnderlyingError=0x1870cad0 "The request timed out."}
Server Code (On Azure)
var fs = require('fs');
var app = require('express')(),
server = require('http').createServer(app),
redis = require("redis"),
Primus = require('primus'),
kue = require("kue");
var haversine = require('haversine')
var finish = require("finish");
var client = redis.createClient(12276, "redis url");
client.auth('password');
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('join', { status: 'connected' });
});
var port = process.env.port || 1337;
server.listen(port);
SOCKET.IO-OBJC CODE
- (void) reconnect
{
[socketIO disconnectForced];
socketIO = [[SocketIO alloc] initWithDelegate:self];
socketIO.useSecure = NO;
[socketIO connectToHost:#"siteurl" onPort:80];
}
I'm having issues while trying to send PhantomJS calls to servers from my Mocha testsuite.
Problem
I'm trying to use PhantomJS to do calls against an endpoint. I have the first call working.
But I have two problems:
The current script runs well for the first time, but consecutive runs when watching some files make the tests fail. Do do I solve this?
This does not seem like a nice way to do these tests, is there a better alternative?
Setup:
Gulp as watcher
gulp-mocha to run tests
phantom-sync to do some end2end testing
Mocha test file (simplified):
if(typeof process != 'undefined') {
var should = require('chai').should();
var _ps = require('phantom-sync');
var phantom = _ps.phantom;
var sync = _ps.sync;
}
describe('Login', function() {
this.timeout(5000);
it('should be able to open CMS', function(done) {
sync(function() {
var ph = phantom.create();
var page = ph.createPage();
var status = page.open('http://www.google.com'); // Get a default CMS url...
status.should.equal('success');
ph.exit();
return done();
});
});
it('should redirect after successful login');
});
Gulpfile (simplified):
gulp.task('test-develop', ['scripts'], function() {
return test(null, true);
});
var keepAlive = false;
function test(reporter, _keepAlive) {
keepAlive = _keepAlive;
return gulp.src('test/**/*.js')
.pipe(plugins.plumber())
.pipe(plugins.mocha({ reporter: reporter || 'spec' })
.on('error', onError));
}
function onError(err) {
console.log(err.toString());
if (keepAlive) {
this.emit('end');
} else {
// if you want to be really specific
process.exit(1);
}
}
gulp.task('watch-test', function() {
gulp.watch('test/**/*.js', ['test-develop']);
});
Errors:
➜ [project_dir] git:(feature/phantomjs-tests) ✗ gulp watch-test
[gulp] Using gulpfile [project_dir]/gulpfile.js
[gulp] Starting 'watch-test'...
[gulp] Finished 'watch-test' after 26 ms
[gulp] Starting 'scripts'...
[gulp] Finished 'scripts' after 530 ms
[gulp] Starting 'test-develop'...
Homepage
Menu
- should open without error
- should close without error
Login
✓ should be able to open CMS (2126ms)
- should capture wrong username
- should capture wrong password
- should capture wrong username & password
- should redirect after successful login
ArtobjectPage
#ArtobjectPage
- should save $container
- should call setupZoom
- should call setupInfoButton
- should call setupObjectData
1 passing (2s)
10 pending
[gulp] Finished 'test-develop' after 2.42 s
[gulp] Starting 'scripts'...
[gulp] Finished 'scripts' after 94 ms
[gulp] Starting 'test-develop'...
Homepage
Menu
- should open without error
- should close without error
Login
1) should be able to open CMS
- should capture wrong username
- should capture wrong password
- should capture wrong username & password
- should redirect after successful login
ArtobjectPage
#ArtobjectPage
- should save $container
- should call setupZoom
- should call setupInfoButton
- should call setupObjectData
0 passing (2ms)
10 pending
1 failing
1) Login should be able to open CMS:
TypeError: undefined is not a function
at sync ([project_dir]/node_modules/phantom-sync/node_modules/make-sync/lib/make-sync.js:132:10)
at Context.<anonymous> ([project_dir]/test/e2e/login.js:13:5)
at Test.Runnable.run ([project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runnable.js:196:15)
at Runner.runTest ([project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:374:10)
at [project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:452:12
at next ([project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:299:14)
at [project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:309:7
at next ([project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:247:23)
at Object._onImmediate ([project_dir]/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:276:5)
at processImmediate [as _immediateCallback] (timers.js:330:15)
[gulp] Error in plugin 'gulp-mocha': 1 test failed.
[gulp] Finished 'test-develop' after 85 ms
It ended up state being evil and Phantom not properly clearing it's cache & cookies when asked to.