[英]Network Error when trying to register with ReactJS
我有一個只有一個字段(用戶名)的注冊表單。 當我嘗試注冊新成員時,我收到了錯誤Error: Network Error
這是我的寄存器 Class
constructor(props) {...}
handleChange(event) {...}
handleSubmit(event) {
const username = this.state.username;
console.log(username);
axios.post("http://localhost:1270/", { username }, { withCredentials: true }
).then(reponse => {
console.log('register', reponse)
});
event.preventDefault();
}
render() {...}
還有我的server.js
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.post('/', (request, reponse) => {
mongo.connect(url, function (err, db) {
var dbo = db.db("mern-pool");
var username = request.body.username;
console.log(username);
var obj = {
username:username
};
dbo.collection("students").insertOne(obj, function(err, result) {
db.close();
reponse.send('inserted');
});
});
});
如果我刪除這部分代碼,我的用戶名將正確插入
{ withCredentials: true }
當axios
請求不返回 200 時,它會引發錯誤。 你必須處理它。 將 axios 調用替換為:
axios.post("http://localhost:1270/", { username }, { withCredentials: true })
.then(reponse => {
console.log('register', reponse);
})
.catch(err => {
console.log('Axios Err', err);
})
然后告訴我們。
這可能是由 CORS 引起的...我已經嘗試手動設置 CORS 的標題但仍然有問題,然后我只是npm install cors
var cors = require('cors')
app.use(cors())
根據您對傑克遜回答的評論,您似乎已啟用Access-Control-Allow-Credentials
以及Access-Control-Allow-Origin
設置為*
。 CORS 不允許 * 和憑據為真,您必須指定http://localhost:1270/
作為 Z8A5DA52ED126447D359E70C05721A8Allow Access-Control-Allow-Credentials: true
C05721A8Allow-憑據中的允許來源
CORS 如果你不知道它的怪癖可能會很痛苦,它基本上會阻止從它無法識別的位置向 api 發出請求。 因此,當您指定*
表示它將允許每個來源、每個來源都能夠訪問 api。 但是,CORS 的一個怪癖是,如果您的 Allow-Origin 是 *,它將不允許Access-Control-Allow-Credentials: true
。 因此,如果您需要這樣做,您需要指定您的客戶端應用程序來源(我認為http://localhost:1270/
)作為接收請求的可接受位置。
希望這有意義並有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.