For some reason it only comes as empty json like:{} (as seen in the output)
I would like if instead I could access the parameters sent from the routes somehow.
Frontend:
let api = axios.create({
baseURL: "http://localhost:5000/validateSignIn",
})
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
// api.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
export default function TopBar(input){
function postCredentials(un, pw){
let params = new URLSearchParams();
params.append('username', un);
params.append('password', pw);
let getResponse = api.get('/', params, config)
.then(response=>{
return (response.data)
}).catch()
return getResponse
}
async function validateSignIn(){
let user = document.getElementById("username").value
let success = await(postCredentials(user, document.getElementById("password").value))
console.log(success)
if(success){
input.setState({"name":user})
return input.setSignedIn(true);
}
else{
console.log("invalid login attempt")
}
}
return(
<div className="signInPage">
<div>Enter UserName: </div>
<input type="username" id="username" maxLength="32" autoComplete="off">
</input>
<div>Enter Password: </div>
<input type="password" id="password" maxLength="32" autoComplete="off">
</input>
<br />
<button onClick={() => validateSignIn()}>Click to sign in</button>
</div>
)
}
Server:
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())
app.all("/", function(req, res, next) {
req.header("Origin", "http://localhost:3000/");
return next();
});
app.use('/login', loginRoutes)
app.use('/validateSignIn', SignInRoutes)
const PORT = process.env.PORT || 5000
Route:
const router = express.Router();
export const getSignin = (req, res) => {
console.log("params:" JSON.stringify(req.params))
console.log("query:" JSON.stringify(req.query))
console.log("body:" JSON.stringify(req.body))
if(!req.username)
res.send(false)
else{res.send(true)}
}
Output:
{
params:{}
query:{}
body:{}
}
Note: The desired output I'm trying for would contain the username and password sent from front end somewhere reachable. I don't mind if it is body, query, params, or somewhere else.
CodePudding user response:
Turns out the answer was that you can't send information in the body when using a GET request, but it works when doing a POST request. Found out after reading API documentation here: https://www.npmjs.com/package/axios#axios-api