I looked some similar questions but mine seems to be different, because it works with postman but it doesn't work with my own fetch - so there's nothing wrong in my backend I think.
This is my frontend:
url = "http://localhost:8081/signup";
op = {
method: "POST",
credentials: 'same-origin',
mode: 'cors',
headers:{
'Content-type': 'application/x-www-form-urlencoded',
'Accept':'application/json'
},
body:JSON.stringify({
user:'myUser',
password:'myPassword123',
email:'myemail@hotmail.com'
}),
};
fetch(url,op)
.then(dados=>dados.json())
.then(dados=>console.log(dados))
You see? I was careful to use x-www-form-urlencoded because i'm using a middleware in nodejs that works with urlencoded:
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
In my fetch request, I was also careful to use what I just learned and I hope I learned right:
credentials: same-origin - because it is running in my localhost, so it's from the same origin and also I want to be able to get the cookies. If it belonged in another origin and I also wanted the cookies I would use include.
Mode: cors - I thought I should use this just to get data from other origin, but since didn't work with no-cors (returned lots of weird things) i'm using cors.
Here goes My code (the part that matters), but I don't think it's my backend because it worked with postman:
const express = require("express");
const app = express();
bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
const cors = require("cors");
app.use(cors())
app.post("/signup",function(req,res){
if(!req.body.email || !req.body.user|| !req.body.password){
const resultado = {
Empty: "Yes",
Email: req.body.email,
User: req.body.user,
Password: req.body.password,
}
res.json(resultado)
exit()
}
tabelaUsuario.create({
user: req.body.user,
email: req.body.email,
password: req.body.password
}).then(()=>{
req.session.email = req.body.email;
res.json(req.body)
}).catch((erro)=>{
res.send("ERRO! erro: "+erro);
})
})
app.listen(8081);