Tuesday, 2 April 2019

Having trouble making a POST request using fetch() in a CRUD application.

Hey all, I'm trying to build a forum but am having some trouble. I have Vue serving the client-side files at :3000, with Express serving the back-end files at :3010.On a register form I have this code which is triggered upon submit:// Vue.prototype.$siteHost = 'http://localhost:3010' in development mode // vals = collected values from register form (username, password etc) fetch(`${Vue.prototype.$siteHost}/register`, { method: 'POST', body: JSON.stringify({values: vals}), headers: { 'Content-Type': 'text/html', }, }) .catch(err => console.log(err)); And in the file which Express runs, server.ts, I have this to handle the POST request:app.post('/register', (req: express.Request, res: express.Response) => { res.type('text/html'); res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST'); res.send(JSON.stringify(req.body)); }); However, I am getting a NetworkError in the console, along with two messages on the CORS being blocked, one stating that the CORS head 'Access-Control-Allow-Origin' is missing and the other stating that the CORS request did not succeed (line 121 of Home.vue is the .catch line). This also occurs if I change the Access-Control-Allow-Origin value to a wildcard '*'.In the Networking panel I can't get past OPTIONS. Response headers are as follows:HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 Accept-Ranges: bytes Cache-Control: public, max-age=0 Last-Modified: Tue, 02 Apr 2019 14:22:28 GMT ETag: W/"136-169de6e1060" Content-Length: 310 Date: Tue, 02 Apr 2019 14:44:45 GMT Connection: keep-alive And request headers are as follows:Host: localhost:3010 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0 Accept: */* Accept-Language: en-GB,en;q=0.5 Accept-Encoding: gzip, deflate Access-Control-Request-Method: POST Access-Control-Request-Headers: content-type Referer: http://localhost:3000/ Origin: http://localhost:3000 DNT: 1 Connection: keep-alive How do I make a successful POST request using fetch?

Submitted April 02, 2019 at 03:52PM by beefyjon

No comments:

Post a Comment