Is it possible to call a fetch in JS to a custom port?
- User
Is it possible to call a fetch in JS to a custom port?
Assistant
Yes, it is absolutely possible to make a
fetchrequest in JavaScript to a server running on a custom port. ThefetchAPI allows you to specify the full URL—including the protocol, hostname, port, and path—as long as the port is open and accessible from the client.Example
fetch('http://localhost:3000/api/data') .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then(data => { console.log('Data received:', data); }) .catch(error => { console.error('Fetch error:', error); });In this example:
localhostis the host.3000is the custom port./api/datais the endpoint path.
Important Notes:
-
Same-Origin Policy (CORS):
- If your frontend JavaScript is served from a different origin (different protocol, domain, or port) than your backend server, you must handle Cross-Origin Resource Sharing (CORS) on the server.
- Otherwise, the browser will block the request due to security restrictions.
-
Secure Contexts (HTTPS):
- If your page is served over HTTPS, calling a non-secure endpoint (
http://...) might be blocked depending on browser settings.
- If your page is served over HTTPS, calling a non-secure endpoint (
-
Firewalls / Network Restrictions:
- Ensure that the custom port is open on the server and not blocked by firewalls or corporate network policies.
-
Browser Support:
fetch()is supported in all modern browsers. For older browsers (like IE), you'd need a polyfill likewhatwg-fetch.
CORS Example (Server-Side with Express.js):
If you're using Node.js/Express, you can enable CORS for all routes like this:
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // Enable CORS for all requests app.get('/api/data', (req, res) => { res.json({ message: 'Hello from custom port!' }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });✅ So yes — just use the full URL with the desired port in your
fetch()call, and ensure your backend is configured to accept cross-origin requests if needed.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.