我使用普通javascript(AJAX(发布表单,并使用Formdata((。表单的提交由nodejs捕获并连接到数据库。
问题是,当我向nodejs发送正常数据时,我能够连接数据库并成功响应。但是,当我添加文件上传输入(存储文件路径(并尝试连接时,CORS错误即将到来。我已经在express(nodejs(中将允许交叉原点的头设置为*值。
HTML:
<div class="form-group">
<label for="textareaLbl2">Description 2</label>
<textarea name="descr2" class="form-control" id="textareaLbl2" rows="3"></textarea>
</div>
<div class="form-group">
<label for="img">Upload:</label>
<input type="file" name="img" class="form-control" id="img" />
</div>
JS:
testForms.onsubmit = function(event) {
event.preventDefault();
var formData = new FormData(testForms);
request.open( "POST", "https://xyz.domain.com/addList", true);
request.send(formData);
}
Nodejs:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// 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');
这行得通吗?如果您没有尝试过cors中间件:https://www.npmjs.com/package/cors
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// 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();
});
也可以尝试在节点侧设置"内容类型"。