邮递员获得res.send响应,但XMLHttpRequest却没有运气

时间:2020-09-17 19:13:26

标签: node.js express xmlhttprequest cors postman

使用Express框架的Node.js上的代码:
发送请求时,服务器控制台上没有错误。
const cp = require("child_process"); var child = cp.spawn( "/usr/bin/inkscape", [ "--with-gui", "--batch-process", "--export-filename=-", "--actions=select-all;ObjectToPath", "/full/path/to/example.svg", ], { cwd: process.cwd(), detached: true, stdio: "inherit", }, );

浏览器中正在使用的JavaScript代码:
在浏览器控制台中,所有这3种代码我一无所获,而不是app.post('/plzWork', function (req, res) { res.send('Got it'); }),但是好像表示null的字符串。

""

对邮递员的预期答复:
screenshot of postman console (Imgur)

我所需要做的就是在控制台中获得“了解”响应,就是这样。
另外,我尝试避免进行提取,但是如果这是 only 的工作方式,那就很好了。

2 个答案:

答案 0 :(得分:0)

默认情况下,您的请求是异步的,您应该订阅事件onreadystatechange并获得结果:

// this line should be before xhr.send
xhr.onreadystatechange = function() {//Calls this function after state is changed.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // Request finished. You can process a result here.
    }
}

请参见MDN

答案 1 :(得分:-1)

浏览器出现此错误:
<preference name="android-targetSdkVersion" value="29" />

要解决此问题,您需要在NPM / node.js上安装CORS。 Access to XMLHttpRequest at 'http://127.0.0.1:6969/plzWork' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
然后将其加载到服务器中:

npm install cors --save

现在可以在浏览器上阅读它了,只是上面的代码是 @Anatoly 的代码。
它看起来应该像这样:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

const port = 6969;
app.listen(port)

app.post('/plzWork', function (req, res) {
     res.send("Got it");
})

进行了这些更改后就可以使用!
在Postman上,在此Express修复之前,获得响应的平均时间为〜11ms。
现在, cors已安装,平均约为3毫秒!

More info about CORS found here.

相关问题