I'm new to node.js and I'm trying to making an api But when i try to do a fatch request from a different url i get an error But if i do a fatch request from the same url it works fine.
The error i get: Error: Failed to fetch
My index.js file:
const express = require('express');
const LimitingMiddleware = require('limiting-middleware');
const app = express();
app.use(new LimitingMiddleware().limitByIp());
app.use(express.static("public"));
app.use('/facts', require('./routes/facts'));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
app.get('/ping', (req, res) => {
res.send('pong');
});
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
type: 'error', message: err.message
});
});
app.listen(3000, () => console.log(`Server Start at 3000 Port`));
The routes/facts.js file:
const express = require('express');
const router = express.Router();
const { randomFact } = require('../fact-handler');
router.get('/random', (req, res) => {
res.json({ api_test: 'Works' });
});
module.exports = router;
You need to provide a relative URL to the fetch()
method when making a request, instead of absolute URL, ie instead of fetch('http://localhost:3000/facts/random')
, use fetch('/facts/random')
, so it will resolve to the host serving the file, allowing you to run it on multiple environments.
Try serving this as index.html
:
<!DOCTYPE html>
<html>
<script>
window.addEventListener('DOMContentLoaded', () => {
// use relative URL to run on any environement
// forward slash indicates that the path is relative to the domain root
fetch('/facts/random', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then((response) => {
// parse JSON response into native JavaScript objects
// return for processing
return response.json();
}).then((response) => {
// success
console.log('it works', response);
document.write(JSON.stringify(response));
}).catch((error) => {
console.error('Error:', error);
});;
});
</script>
<head>
<title></title>
</head>
<body>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.