The problem
I have this fake API:
[{"task_id":"44","task_title":"task1"},{"task_id":"45","task_title":"task2"},{"task_id":"46","task_title":"task1"},{"task_id":"47","task_title":"task2"}]
When I try to access it using a fetch GET method, using the code below:
function getData(){
fetch('http://localhost:5000/api/tasks')
.then(res => res.json())
.then((data) => {console.log(data)});}
getData();
I get the expected result in the console.
(4) [{…}, {…}, {…}, {…}]
0: {task_id: '44', task_title: 'task1'}
1: {task_id: '45', task_title: 'task2'}
2: {task_id: '46', task_title: 'task1'}
3: {task_id: '47', task_title: 'task2'}
Yet, when I try to access it through a POST method, like so:
function postData(){
fetch('http://localhost:5000/api/tasks',{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
task_title: 'testTask'
})
})
.then(res =>{
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log('ERROR'))
}
I get this unexpected 404:
POST http://localhost:5000/api/tasks 404 (Not Found)
My API is set as so using Node.js and express:
app.get('/api/tasks', (req, res)=>{
db.SelectAll().then(data => {res.json(data)});
})
db is just:
const db = require('./db/db.js');
and SelectAll() is:
async function SelectAll() {
try {
const res = await client.query("SELECT * FROM tasks");
return res.rows;
} catch(err){
console.log(err);
}
client.end();
};
What is causing this 404?
app.get('/api/tasks', (req, res)=>{ db.SelectAll().then(data => {res.json(data)}); })
Your code registers a GET handler. You have not used app.post to register a POST handler.
While this should mean that a POST request to that path gets a 405 Method Not Allowed response, Express does not support this automatically and gives a 404 Not Found instead.
If you want to do something when a POST request is made to that path, then you need to use app.post to register a function that will run and do whatever it is that you want to do.