ReactJS/Express Axios POST returns 404,来自 Postman 的作品
ReactJS/Express Axios POST returns 404, works from Postman
我不知道我做错了什么。 POST 方法适用于 Postman,但不适用于 React 前端。
users.js (/api/users/login)
// @route POST api/users/login
// @desc Login user / Returning JWT Token
// @access Public
router.post('/login', (req, res, next) => {
const { errors, isValid } = validateLoginInput(req.body);
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
// Find user by email
User.findOne({ email }) // matching email: email
.then(user => {
if (!user) {
errors.email = 'User not found';
return res.status(404).json(errors);
}
// Check Password
bcrypt.compare(password, user.password)
.then(isMatch => {
if(isMatch) {
// User matched. Create JWT payload
const payload = {
id: user.id
}
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: 'Bearer ' + token
});
});
} else {
errors.password = 'Password incorrect'
return res.status(400).json(errors);
}
});
});
});
loginUser() 函数:
export const loginUser = userData => dispatch => {
axios
.post("/api/users/login", userData)
.then(res => {
// Save to localStorage
const { token } = res.data;
// Set token to localStorage
localStorage.setItem("jwtToken", token); // only stores strings
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
React 组件中的 onSubmit() 函数:
onSubmit(e) {
e.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
}
this.props.loginUser(userData);
}
网络:
Request URL: http://localhost:3000/api/users/login
Request Method: POST
Status Code: 404 Not Found
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Length: 155
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Mon, 16 Jul 2018 01:53:03 GMT
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 46
Content-Type: application/json;charset=UTF-8
Cookie: io=VtWk-hb742jVakwrAAAE; PHPSESSID=ige5g7257th8hiksjomg2khouu; i18next=en; connect.sid=s%3Aq6FkEveJbDYoKTy386QESFBxGaW8MjKd.qSBAkm2t23Ww4ZtHtcs7%2F1e5tDn528i0C6Hv7U3PwI0
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
{email: "admin@gmail.com", password: "admin"}
email
:
"admin@gmail.com"
password
:
"admin"
server.js上的端口:
// Initializint the port
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
这里查了一些类似的问题,大部分都和headers有关。在我的例子中,headers 是 application/json,所以我认为问题不在那里。通过 Postman 访问端点没有问题。
您的 React 应用程序 运行 与您的后端应用程序位于不同的端口。 create-react-app
在端口 3000 上运行,正如您所说,您的后端是 运行 在端口 5000 上。
当您的客户端应用程序向服务器发出请求时,它实际上是向端口 3000 发出请求,如您在此处所见。
Request URL: http://localhost:3000/api/users/login
这样做是因为您从未在请求中指定来源 url,如您在此处所见 post("/api/users/login", userData)
,在这种情况下,它默认为与请求来自的端口相同的端口3000,而端口 3000 实际上没有您请求的 url。
您可以通过在请求中包含来源 url 或向 React 应用程序添加代理 package.json 来解决此问题。
我不知道我做错了什么。 POST 方法适用于 Postman,但不适用于 React 前端。
users.js (/api/users/login)
// @route POST api/users/login
// @desc Login user / Returning JWT Token
// @access Public
router.post('/login', (req, res, next) => {
const { errors, isValid } = validateLoginInput(req.body);
// Check validation
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
// Find user by email
User.findOne({ email }) // matching email: email
.then(user => {
if (!user) {
errors.email = 'User not found';
return res.status(404).json(errors);
}
// Check Password
bcrypt.compare(password, user.password)
.then(isMatch => {
if(isMatch) {
// User matched. Create JWT payload
const payload = {
id: user.id
}
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: 'Bearer ' + token
});
});
} else {
errors.password = 'Password incorrect'
return res.status(400).json(errors);
}
});
});
});
loginUser() 函数:
export const loginUser = userData => dispatch => {
axios
.post("/api/users/login", userData)
.then(res => {
// Save to localStorage
const { token } = res.data;
// Set token to localStorage
localStorage.setItem("jwtToken", token); // only stores strings
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
React 组件中的 onSubmit() 函数:
onSubmit(e) {
e.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
}
this.props.loginUser(userData);
}
网络:
Request URL: http://localhost:3000/api/users/login
Request Method: POST
Status Code: 404 Not Found
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Length: 155
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Mon, 16 Jul 2018 01:53:03 GMT
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 46
Content-Type: application/json;charset=UTF-8
Cookie: io=VtWk-hb742jVakwrAAAE; PHPSESSID=ige5g7257th8hiksjomg2khouu; i18next=en; connect.sid=s%3Aq6FkEveJbDYoKTy386QESFBxGaW8MjKd.qSBAkm2t23Ww4ZtHtcs7%2F1e5tDn528i0C6Hv7U3PwI0
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
{email: "admin@gmail.com", password: "admin"}
email
:
"admin@gmail.com"
password
:
"admin"
server.js上的端口:
// Initializint the port
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
这里查了一些类似的问题,大部分都和headers有关。在我的例子中,headers 是 application/json,所以我认为问题不在那里。通过 Postman 访问端点没有问题。
您的 React 应用程序 运行 与您的后端应用程序位于不同的端口。 create-react-app
在端口 3000 上运行,正如您所说,您的后端是 运行 在端口 5000 上。
当您的客户端应用程序向服务器发出请求时,它实际上是向端口 3000 发出请求,如您在此处所见。
Request URL: http://localhost:3000/api/users/login
这样做是因为您从未在请求中指定来源 url,如您在此处所见 post("/api/users/login", userData)
,在这种情况下,它默认为与请求来自的端口相同的端口3000,而端口 3000 实际上没有您请求的 url。
您可以通过在请求中包含来源 url 或向 React 应用程序添加代理 package.json 来解决此问题。