Reputation: 1348
I'm trying to pass a data from my client to server side script, but my program reply POST http://localhost:3005/v1/account/login 400 (Bad Request)
, but whenever I try it on postman, it always work properly,
This is my code for requesting post data to my NodeJS server using my ReactJS application:
fetch(config.endPoint.login, {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: {
username: this.state.username,
password: this.state.password
}
}).then((response) => {
if(response.error_code == 0) {
console.log(response);
this.props.history.push("/main");
} else {
alert('login failed!');
}
}).catch((err) => {
console.log(err);
alert('Error\nplease check your network connection and try agian!');
});
well I use that request when I'm creating a react-native app from my previous projects and it works well, so I don't think that there's something wrong about my method of requesting a data to server
This is my controller that handles the api request on that login route
// '/v1/account/login'
api.post('/login', passport.authenticate(
'local', {
session: false,
scope: []
}
), generateAccessToken, respond);
And this is my middleware that handles that api requests and response
let authenticate = expressJwt({secret: SECRET});
let generateAccessToken = ( req, res, next ) => {
req.token = req.token || {};
req.token = jwt.sign({
id: req.user.id
}, SECRET, {
expiresIn: TOKENTIME
});
next();
}
let respond = (req, res) => {
Account.findOne({_id: req.user._id}, (err, account) => {
if(err) {
res.send(err)
}
let user_token = sha256.x2(Math.floor(new Date() / 1000) + account._id + config.serverCode + config.serverKey)
account.user_token = user_token;
account.save(err => {
if(err) {
res.send(err);
}
res.status(200).json({
status: 'success',
error_code: 0,
user_token: user_token,
user_id: req.user._id,
user: req.user.username,
token: req.token
});
});
});
}
And then, I'm having an error saying that Access to fetch at 'http://localhost:3005/v1/account/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So I researched and found to write this code at my index.js
file
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
And now, I'm having an error saying POST http://localhost:3005/v1/account/login 400 (Bad Request)
And I researched and see someone says that
bad request means that you're trying to fetch data from request object using invalid keys. see here
but I can't see the wrong data that I'm passing,
I pass data using postman in this format:
{
"username": "yoyo929",
"password": "12345678"
}
And it works well, what's the wrong with my codes?
I'm also seeing this error at my nodejs terminal
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at parse (F:\project\galaxy\node_modules\body-parser\lib\types\json.js:89:19)
at F:\project\galaxy\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (F:\project\galaxy\node_modules\raw-body\index.js:224:16)
at done (F:\project\galaxy\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (F:\project\galaxy\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
Upvotes: 0
Views: 6044
Reputation: 11857
The data you are passing to fetch must be stringified, otherwise something like [object Object]
will be passed in:
fetch(config.endPoint.login, {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
}).then((response) => {
if(response.error_code == 0) {
console.log(response);
this.props.history.push("/main");
} else {
alert('login failed!');
}
}).catch((err) => {
console.log(err);
alert('Error\nplease check your network connection and try agian!');
});
Hope this helps!
Upvotes: 6